如何在Blackberry中执行http get请求

时间:2012-05-18 14:43:29

标签: java json blackberry

我必须在URL http://api.twitter.com/1/users/show.json?screen_name=Kaka上执行http GET请求,我将获得一个JSON对象,但我不知道我该怎么做。

有人可以帮助我吗?

谢谢你。

1 个答案:

答案 0 :(得分:3)

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数据解压缩为JSONObjects和JSONArrays的代码可能与上面的内容略有不同,具体取决于结构你自己的JSON数据。