2012-05-20 171 views
2

我正在使用JSON的Web服务应用程序。 在执行任务时,我通过点击URL直接获取JSOn响应成功。json解析黑莓手机?

现在我有一个任务请求一个请求参数。

enter code here 
private void callJSON_Webservice(String method,String paraLastModifiedDate) { 
     HttpConnection c=null; 
     InputStream is = null; 
     String feedURL = Constants.feedURL; 
     int rc; 

     try{ 
      JSONObject postObject = new JSONObject(); 
      postObject.put("CheckLatestDataDate",method); 
      postObject.put("LastModifiedDate", paraLastModifiedDate); 
      //c = new HttpConnectionFactory().getHttpConnection(feedURL); 
      c = (HttpConnection)Connector.open(feedURL + ConnectionManager.getConnectionString()); 

      // Set the request method and headers 
      c.setRequestMethod(HttpConnection.GET); 
      c.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
      c.setRequestProperty("Content-Length", "" + (postObject.toString().length() - 2)); 
      //c.setRequestProperty("method", HttpConnection.GET); 

      // Getting the response code will open the connection, 
      // send the request, and read the HTTP response headers. 
      // The headers are stored until requested. 
      rc = c.getResponseCode(); 

      if (rc != HttpConnection.HTTP_OK){ 
       throw new IOException("HTTP response code: " + rc); 
      } 

      is = c.openInputStream(); 

      String json = StringUtils.convertStreamToString(is); 
      object = new JSONObject(json); 


     }catch (Exception e) { 
      System.out.println(e+"call webservice exception"); 
     } 

    } 

有了这段代码,我得到了EOF异常。我需要尽快完成这项小任务。请帮帮我...! Thanx提前

回答

2

尝试用以下替换

is = c.openInputStream(); 

String json = StringUtils.convertStreamToString(is); 

is = c.openInputStream(); 

StringBuffer buffer = new StringBuffer(); 
int ch = 0; 
while (ch != -1) { 
    ch = is.read(); 
    buffer.append((char) ch); 
} 

String json = buffer.toString(); 


参考:convert StreamConnection to String

+0

Rupak,我在JSON和XML发送请求的参数很困惑,我已经通过发布请求参数来执行XML解析,但无法用JSON完成。请从核心提供一些示例代码或片段来指导我。 –

+1

检查这些链接,http://stackoverflow.com/questions/10380400/json-send-post-error-in-blackberry,http://stackoverflow.com/questions/9339656/send-json-request-from-blackberry -application,http://stackoverflow.com/questions/7531822/http-post-with-blackberry-6-0-issue,http://supportforums.blackberry.com/t5/Java-Development/How-to-POST -JSON/td-p/587757 – Rupak

+0

thanz很多Rupak,这真的是一个很大的帮助...!我完成了这项任务。并获得我的数据。向服务器发送请求的步骤与xml解析的步骤相似,只需要处理我们将以JSON形式获得的响应。在我的脑海中为整个人生而设置。感谢社区。 –