2012-06-04 96 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

相关问题