![](/img/trans.png)
[英]MultipartEntityBuilder HttpPost socket write error in java
[英]HttpPost returning error when using MultipartEntityBuilder in Android
我正在嘗試查詢“ 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中使用帶有文件對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.