How to send image with post request

18,239

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);
}
Share:
18,239
Damir
Author by

Damir

Updated on August 01, 2022

Comments

  • Damir
    Damir almost 2 years

    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 ?