What are the best methods to consume a web service

2020-06-30 04:15发布

问题:

Can anyone tell me which is the best, ease and flexible method to consume web service from android? I'm using eclipse.

回答1:

Since you only care about consuming a webservice, I assume you already know how to send data from the web server. Do you use JSON or XML, or any other kind of data format?

I myself prefer JSON, especially for Android. Your question still lacks some vital information.

I personally use apache-mime4j and httpmime-4.0.1 libraries for web services.

With these libraries I use the following code

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) {}
    }
}

I make a request via _client.execute([method], [extra optional params]) The result from the request is put in a HttpResponse object.

From this object you can get the status code and the entity containing the result. From the entity I take the content. The content would in my case be the actualy JSON string. You retrieve this as an InputStream, convert the stream to a string and do whatever you want with it.

For example

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

Depending on how you build your JSON. mine is nested deeply with objects in the array etc. But handling this is basic looping.

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

You can extract data from the current JSON object in this case like:

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


回答2:

to parse "JSON" I recommend the following library is the faster and better.

Jackson Java JSON-processor