2012-06-04 91 views

回答

2

由於您只關心消費Web服務,我假設您已經知道如何從Web服務器發送數據。你使用JSON還是XML,或者其他類型的數據格式?

我自己更喜歡JSON,特別是Android。 您的問題仍然缺乏一些重要信息。

我個人使用apache-mime4j和httpmime-4.0.1庫進行web服務。

隨着這些庫我使用以下代碼

public void get(String url) { 
    HttpResponse httpResponse = null; 
    InputStream _inStream = null; 
    HttpClient _client = null; 
    try { 

     _client = new DefaultHttpClient(_clientConnectionManager, _httpParams); 
     HttpGet get = new HttpGet(url); 

     httpResponse = _client.execute(get, _httpContext); 
     this.setResponseCode(httpResponse.getStatusLine().getStatusCode()); 

     HttpEntity entity = httpResponse.getEntity(); 
     if(entity != null) { 
      _inStream = entity.getContent(); 
      this.setStringResponse(IOUtility.convertStreamToString(_inStream)); 
      _inStream.close(); 
      Log.i(TAG, getStringResponse()); 
     } 
    } catch(ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      _inStream.close(); 
     } catch (Exception ignore) {} 
    } 
} 

我使經由_client.execute的請求([方法],[附加可選PARAMS]) 從請求的結果被放入HttpResponse對象。

從這個對象中你可以得到狀態碼和包含結果的實體。 從實體我拿的內容。內容將在我的情況下是實際的JSON字符串。您將其作爲InputStream檢索,將該流轉換爲字符串並根據需要執行任何操作。

例如

JSONArray result = new JSONArray(_webService.getStringResponse()); //getStringResponse is a custom getter/setter to retrieve the string converted from an inputstream in my WebService class. 

取決於你如何建立你的JSON。我與數組中的對象深深嵌套等。 但處理這是基本的循環。

objectInResult.getString("name"); //assume the json object has a key-value pair that has name as a key. 
0

解析「JSON」我建議以下庫是更快,更好:

JSONObject objectInResult = result.getJSONObject(count);//count would be decided by a while or for loop for example. 

您可以像在這種情況下,提取從目前的JSON對象數據。

Jackson Java JSON-processor

相關問題