Java 如何在Blackberry中执行http get请求
我必须对URL执行一个HTTPGET请求,然后我将得到一个JSON对象,但我不知道我必须怎么做 有人能帮我吗 谢谢你。 或者,使用Java 如何在Blackberry中执行http get请求,java,json,blackberry,Java,Json,Blackberry,我必须对URL执行一个HTTPGET请求,然后我将得到一个JSON对象,但我不知道我必须怎么做 有人能帮我吗 谢谢你。 或者,使用org.json.me: HttpConnection conn=null; InputStream in=null; ByteArrayOutputStream out=null; 试一试{ 字符串url=”http://api.twitter.com/1/users/show.json?screen_name=Kaka"; conn=(HttpConnection
org.json.me
:
HttpConnection conn=null;
InputStream in=null;
ByteArrayOutputStream out=null;
试一试{
字符串url=”http://api.twitter.com/1/users/show.json?screen_name=Kaka";
conn=(HttpConnection)Connector.open(url,Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code=conn.getResponseCode();
if(code==HttpConnection.HTTP\u OK){
in=conn.openInputStream();
out=新的ByteArrayOutputStream();
byte[]buffer=新字节[in.available()];
int len=0;
而((len=in.read(buffer))>0){
输出。写入(缓冲区);
}
out.flush();
字符串响应=新字符串(out.toByteArray());
JSONObject resObject=新JSONObject(响应);
String key=resObject.getString(“插入Json键”);
向量结果向量=新向量();
JSONArray JSONArray=resoobject.getJSONArray(“插入Json数组键”);
if(jsonArray.length()>0){
for(int i=0;i
显然,在第二个示例中,您必须插入JSON数据实际使用的JSON键的名称(作为海报的练习)。此外,您可能还了解JSON对象的结构,如对象和数组等。因此,将JSON数据解包到JSONObject和JSONArray中的代码可能与上面的代码略有不同,取决于您自己的JSON数据的结构。检查SDK中的示例,他们有一个执行request.Upvoting的好例子。回答得很好,内特。如果你有时间的话,可以看看这个问题吗?类似:嘿@Nate,有没有机会看看这个问题?@donparalias,我同意adwiv对这个问题的回答(另外,请看我在回答下面的评论)。
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
String url = "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
JSONObject resObject = new JSONObject(response);
String key = resObject.getString("Insert Json Key");
Vector resultsVector = new Vector();
JSONArray jsonArray = resObject.getJSONArray("Insert Json Array Key");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length();i++) {
Vector elementsVector = new Vector();
JSONObject jsonObj = jsonArray.getJSONObject(i);
elementsVector.addElement(jsonObj.getString("Insert Json Array Element Key1"));
elementsVector.addElement(jsonObj.getString("Insert Json Array Element Key2"));
resultsVector.addElement(elementsVector);
}
}
}
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (conn != null) {
conn.close();
}
}