我必须对 URL http://api.twitter.com/1/users/show.json?screen_name=Kaka 做一个 http GET 请求我会得到一个 JSON 对象,但我不知道该怎么做。
谁能帮帮我?
谢谢。
最佳答案
This BlackBerry code sample shows how you do that
或者,From another fairly simple example ,它使用 org.json.me
package added to BlackBerry Java 6.0 :
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 数据。
关于java - 我如何在 Blackberry 中执行 http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10654745/