0

我想在模拟器上获得 JSON 响应。如何从服务器读取 JSON?

public void run()
{
      HttpConnection httpConn;
      ConnectionFactory connFact = new ConnectionFactory();
      ConnectionDescriptor connDesc;

      connDesc = connFact.getConnection("http://example.com/login.php");

      if (connDesc != null)
      {
          try {  
                  httpConn = (HttpConnection)connDesc.getConnection();
                  final int iResponseCode = httpConn.getResponseCode();

                  Dialog.alert("Type: "+httpConn.getType());

                  UiApplication.getUiApplication().invokeLater(new Runnable()
                  {
                      public void run()
                      {
                          Dialog.alert("Response code: " +  Integer.toString(iResponseCode)); 
                      }
                  });                         
           } 
           catch (IOException e) 
           {
                 System.err.println("Caught IOException: "  + e.getMessage());
           }
      }
}
4

1 回答 1

1
HttpConnection connection = (HttpConnection)Connector.open(urlConection);
InputStream  inputStream = connection.openInputStream();
if(connection.getResponseCode() == HttpConnection.HTTP_OK){
    InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
    int readCharacter;
    StringBuffer responseBuffer = new StringBuffer();
    while ((readCharacter = reader.read()) != -1) {
        responseBuffer.append((char) readCharacter);
        connection.close();
        inputStream.close();
        reader.close();
        String responseMessage = new String(responseBuffer);
    }
}

您需要为响应创建 JSONObject。

try {
    JSONObject object = new JSONObject(responseMessage);
} catch (JSONException e) {
    e.printStackTrace();
}
于 2012-11-13T18:51:05.860 回答