[英]How can i do a http get request in Blackberry
我必須在URL http://api.twitter.com/1/users/show.json?screen_name=Kaka上做一個http GET請求,我將得到一個JSON對象,但我不知道我怎么做做到這一點。
有人可以幫幫我嗎?
謝謝。
或者, 從另一個相當簡單的示例中 ,它使用添加到BlackBerry Java 6.0的org.json.me
包 :
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();
}
}
顯然,在第二個示例中,您必須插入JSON數據實際使用的JSON密鑰的名稱(作為海報的練習)。 此外,您可能對JSON對象的結構,對象和數組等有所了解。因此,將JSON數據解壓縮為JSONObjects和JSONArrays的代碼可能與上面的內容略有不同,具體取決於結構你自己的JSON數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.