2

我正在尝试在 Android 中使用 MultiPartEntity 和 HttpClient 发送图像,但不断收到异常:java.lang.UnsupportedOperationException: Multipart form entity does not implement #getContent()

这是我的代码:

public boolean enrollImage(String id, byte[] image) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("https://example.com/"+id+"/images/");
    httpPost.addHeader("Authorization", "Basic " + Base64.encodeToString(("user"+":"+"password").getBytes(),Base64.NO_WRAP));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("image", new ByteArrayBody(image, "image/jpg", "image.jpg"));
    httpPost.setEntity(entity);
    HttpResponse response;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String responseString = EntityUtils.toString(entity);
        JSONObject json = new JSONObject(responseString);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return true;
}

我已将较新的 Apache 库httpmime-4.2.5.jarhttpclient-4.2.5.jarhttpcore-4.2.4.jar和添加apache-mime4j-core-0.7.2.jar到我的项目中。

我怎样才能让它运行,以便我可以发布

4

1 回答 1

2

事实证明,我只是将我发送的请求实体与我想解析为 json 的响应实体混淆了。该代码的第 12 行应该是

String responseString = EntityUtils.toString(responseEntity);

不是

String responseString = EntityUtils.toString(entity);

问题已解决。猜猜我是时候买一只橡皮鸭了

于 2013-05-31T20:31:36.697 回答