1

次のように、AndroidからJerseyサーバーにマルチパートメッセージを送信できました。

File file = new File(imagePath);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    FileBody fileContent = new FileBody(file);
    MultipartEntity multipart = new MultipartEntity();
    multipart.addPart("file", fileContent);

    try {
        multipart.addPart("string1", new StringBody(newProductObjectJSON));
        multipart.addPart("string2", new StringBody(vitaminListJSON));
        multipart.addPart("string3", new StringBody(mineralListJSON));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    httppost.setEntity(multipart);
    HttpResponse response = null;
    response = httpclient.execute(httppost);
    String statusCode = String.valueOf(response.getStatusLine().getStatusCode());
    Log.w("Status Code", statusCode);
    HttpEntity resEntity = response.getEntity();

    Log.w("Result", EntityUtils.toString(resEntity));

それは正常に機能していますが、問題は、GET を使用してサーバーからマルチパート応答を受信する必要がある場合です。サーバーは、1 つの画像と 3 つの文字列をマルチパート メッセージとして送信する必要もあります。それを処理する方法がわかりません:

HttpResponse response = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    try {
        response = httpclient.execute(httpget);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpEntity resEntity = response.getEntity();
    Log.w("Result", EntityUtils.toString(resEntity));

エンティティから値を抽出する方法がわかりません。応答からそのファイルと文字列の値を取得する方法は? 通常の文字列や JSON などの単純な応答を処理する方法は知っていますが、これはマルチパート応答では気になります。どんなアドバイスも本当に役に立ちます。ありがとうございました。

4

1 に答える 1

2

クライアント側でマルチパート コンテンツを消費する標準的な方法はありません。JAX-RS 仕様は、主にサーバー/リソース エンドに焦点を当てています。ただし、結局のところ、JAX-RS エンドポイントとの通信は、通常の HTTP サーバーとの通信とほぼ同じであり、マルチパート HTTP 応答を処理するための既存の手段はすべて機能します。Java クライアントの世界では、mime4jなどのサードパーティ ライブラリを使用してマルチパート レスポンスを処理するのが一般的ですが、Jersey でこれを行う簡単な方法があります。このソリューションは、JavaMail API (他のソースの中でも特にMaven経由でアクセス可能) に依存しています。

final ClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
        Boolean.TRUE);
final Client client = Client.create(config);

final WebResource resource = client
        .resource(URL_HERE);
final MimeMultipart response = resource.get(MimeMultipart.class);

// This will iterate the individual parts of the multipart response
for (int i = 0; i < response.getCount(); i++) {
    final BodyPart part = response.getBodyPart(i);
    System.out.printf(
            "Embedded Body Part [Mime Type: %s, Length: %s]\n",
            part.getContentType(), part.getSize());
}

取得したら、クライアント コードに応じて個々のボディ パーツを処理できます。

于 2013-02-26T22:00:20.793 に答える