Android uploads image files through HTTP POST

Source: Internet
Author: User

Sending images can be done using the httpcomponents libraries. download the latest httpclient (currently 4.0.1) binary with dependencies package and copyapache-mime4j-0.6.jarAndhttpmime-4.0.1.jarTo your project and add them to your Java build path.

You will need to add the following imports to your class.

import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;

Now you can createMultipartEntityTo attach an image to your POST request. The following code shows an example of how to do this:

public void post(String url, List<NameValuePair> nameValuePairs) {    HttpClient httpClient = new DefaultHttpClient();    HttpContext localContext = new BasicHttpContext();    HttpPost httpPost = new HttpPost(url);    try {        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);        for(int index=0; index < nameValuePairs.size(); index++) {            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {                // If the key equals to "image", we use FileBody to transfer the data                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));            } else {                // Normal string data                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));            }        }        httpPost.setEntity(entity);        HttpResponse response = httpClient.execute(httpPost, localContext);    } catch (IOException e) {        e.printStackTrace();    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.