Problem with multi-page request in android - BAD REQUEST throw

private void CreateaMultiPartRequest() { try{ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://172.16.22.232:8080/RESTfulExample/rest/multiPartFileUpload"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); post.setHeader("Content-type", "multipart/form-data; boundary="+"~~~~~"); String Usersettings = "{\"uId\":\"atcc02\", \"bomId\":\"IC014654_12345\", \"fileName\":\"file_12345.pdf\"}"; File cfile = new File(receivedUri.getPath()); reqEntity.addPart("file", new FileBody(cfile,"application/octet")); reqEntity.addPart("settings", new StringBody(Usersettings,"application/json",Charset.forName("UTF-8"))); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } else{ } } catch(Exception e) { } } 

Whenever I try to execute this code, iam gets "400: BAD REQUEST" from the server. It is not possible to solve this problem here, can someone help me in fixing this problem?

+4
source share
2 answers

Perhaps you are using the wrong MIME type for FileBody. Instead, try the app / octet stream.

To get the correct MIME type, I use the following code:

 MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension); 

Check out my little library that I use to create network requests: http://code.google.com/p/android-dman/source/browse/trunk/src/org/nkuznetsov/lib/dman/DownloadManager.java

0
source

Here you can try it, it works well for me.

  HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); FileBody bin = new FileBody(new File(args[5])); long size = bin.getContentLength(); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("image1", bin); String content = ""; try { httpPost.setEntity(reqEntity); HttpResponse response = httpClient.execute(httpPost, localContext); HttpEntity ent = response.getEntity(); InputStream st = ent.getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(st, writer); content = writer.toString(); } catch (IOException e) { } 
0
source

Source: https://habr.com/ru/post/1480935/


All Articles