从Android使用Web服务的最佳方法是什么?

时间:2012-06-04 09:17:15

标签: android eclipse web-services

任何人都可以告诉我从Android使用Web服务的最佳,简便和灵活的方法是什么?我正在使用eclipse。

2 个答案:

答案 0 :(得分: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([方法],[额外的可选参数])发出请求 请求的结果放在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的方式。我深深地嵌入了数组中的对象等。 但处理这个是基本的循环。

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

在这种情况下,您可以从当前JSON对象中提取数据,如:

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

答案 1 :(得分:0)

解析“JSON”我建议以下库越快越好。

Jackson Java JSON-processor

相关问题