-3

谁能告诉我从 android 使用 Web 服务的最佳、简便和灵活的方法是什么?我正在使用日食。

4

2 回答 2

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([method], [extra optional 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。我的与数组等中的对象嵌套得很深。但处理这个是基本的循环。

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.
于 2012-06-04T09:28:48.817 回答
0

解析“JSON”我推荐以下库更快更好。

Jackson Java JSON 处理器

于 2012-06-04T12:59:51.480 回答