-3

AndroidからWebサービスを利用するための、最も簡単で柔軟な方法はどれですか?エクリプスを使用しています。

4

2 に答える 2

2

あなたは Web サービスを利用することしか考えていないので、Web サーバーからデータを送信する方法を既に知っていると思います。JSON、XML、またはその他の種類のデータ形式を使用していますか?

私自身、特に Android では JSON を好みます。あなたの質問には、まだいくつかの重要な情報が欠けています。

個人的には、Web サービス用に apache-mime4j および httpmime-4.0.1 ライブラリを使用しています。

これらのライブラリでは、次のコードを使用します

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 に答える