3

I need to send post request with data in format like key=value and I am working that like ( url is url of ws and that is ok )

 HttpEntityEnclosingRequestBase post=new HttpPost();
 String result = "";
 HttpClient httpclient = new DefaultHttpClient();
 post.setURI(URI.create(url));
 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
 for (Entry<String, String> arg : args.entrySet()) {
    nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
                    .getValue()));
    }
 http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 HttpResponse response;
 response = httpclient.execute(post);
 HttpEntity entity = response.getEntity();
 if (entity != null) {
    InputStream instream = entity.getContent();
    result = getStringFromStream(instream);
    instream.close();
    }    
 return result;

This is ok when I send String data. My question is what to modify when one parameter is picture adn others are strings ?

Uttam
  • 12,361
  • 3
  • 33
  • 30
Damir
  • 54,277
  • 94
  • 246
  • 365

3 Answers3

1

When you are using multiple data types to send over a HttpClient you must use MultipartEntityBuilder(Class in org.apache.http.entity.mime)

try this out

MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
0

If you are looking to send the image as the data portion of the post request, you can follow some of the links posted in the comments.

If the image / binary data must absolutely be a header (which I wouldn't recommend), then you should use the encodeToString method inside of the Base64 Android class. I wouldn't recommend this for big images though since you need to load the entire image into memory as a byte array before you can even convert it to a string. Once you convert it to a string, its also 4/3 its previous size.

Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47
0

I think the answer you're looking for is in this post:

How to send an image through HTTPPost?

Emmanuel

Community
  • 1
  • 1
Emmanuel
  • 16,791
  • 6
  • 48
  • 74
  • If your entire answer consists of a link to a post you need to summarize it. Otherwise if the link ever breaks the answer is completely useless. – Jess May 17 '19 at 15:24