HttpPost在Android中使用MultipartEntityBuilder时返回错误



我正在尝试查询"http://www.idmypill.com/api/id/"api,而我收到的JSON字符串是{"results":[],"success":false,"errors":null}这是我的服务处理程序类:

public String makeServiceCall(String url, int method, 
        String api, byte[] pillImage) 
{
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
         if (method == POST) 
        {
            android.os.Debug.waitForDebugger();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("data = api_key", api); 
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("files = image", pillImage); 
            entity = builder.build();
            Log.d("Entity", entity.toString()); 
            httpPost.setEntity(entity);
            Log.d("post", httpPost.toString()); 
            httpResponse = httpClient.execute(httpPost);
            Log.d("params", httpResponse.getParams().toString()); 
        } 
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

该网站给出的python示例是:

# highly suggested to use the requests package
# http://www.python-requests.org/en/latest/
import requests
# read in the image and construct the payload
image = open("example.jpg").read()
data = {"api_key": "KH8hdoai0wrjB0LyeA3EMu5n4icwyOQo"}
files = {"image": open("example.jpg")}
# fire off the request
r = requests.post("http://www.idmypill.com/api/id/",
    data = data,
    files = files)
# contents will be returned as a JSON string
print r.content

不知怎么的,我发布的格式一定是错误的,或者他们可能特别想要.jpg图像而不是字节数组吗?我不熟悉Python,已经解决这个问题一个多星期了,所以如果有任何帮助,我将不胜感激。

尝试:

 ...
 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
 builder.addTextBody("api_key", api);
 builder.addPart("image", pillImage); 
 ...

如果addPart不适用于字节数组(我正在工作,无法测试),那么获取图像文件的名称并执行此操作肯定会起作用:

 ...
 pillImage = "/path/to/the/image.jpg";  //This is the image file name
 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
 builder.addTextBody("api_key", api);
 File imageFile = new File(pillImage);  //Open the image
 builder.addPart("image", imageFile); 
 ...

builder.addPart("file",new FileBody(new file(filename)));

请尝试此操作,而不是仅使用addPart 中的文件对象

相关内容

  • 没有找到相关文章

最新更新