2012-05-20 205 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形式獲得的響應。在我的腦海中爲整個人生而設置。感謝社區。 –