HttpPost returns error when using MultipartEntityBuilder in Android

I am trying to execute the request http://www.idmypill.com/api/id/ "api, and the JSON string I get is {"results":[],"success":false,"errors":null} This is my service handler class:

 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; } 

An example python that gives a website:

 # 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 

Somehow, my publication format should be wrong or is it possible that they specifically want to get a .jpg image instead of a byte array? I am not familiar with Python and have been struggling with this problem for more than a week, so any help would be greatly appreciated.

+1
java json python multipartentity
Oct 21 '14 at 7:10
source share
2 answers

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

Try this instead of just using the file object with addPart

0
Oct 22 '14 at 0:17
source
β€” -

Try:

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

If addPart does not work with a byte array (I am at work, I can’t check), taking the image file name, and this will certainly work:

  ... 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); ... 
+1
Oct 21 '14 at 8:24
source



All Articles