How To Simulate An Image Attachment HTTP Multipart POST

Below is the code i use for simulating an image attachment using apache http client.

package com.edw.postsimulator;

import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
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;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class PostTest {

    private static String url = "http://localhost:8083/RealsAppApi/images/add";

    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpContext localContext = new BasicHttpContext();
        Charset chars = Charset.forName("UTF-8");
        // http content
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("username", new StringBody("edwin", chars));
        entity.addPart("password", new StringBody("edwinpassword", chars));        
        // attach image
        File fileToUpload = new File("F:\\no.jpg");
        FileBody fileBody = new FileBody(fileToUpload, "application/octet-stream");
        entity.addPart("image", fileBody);

        // fire and log the responses
        HttpResponse response = httpclient.execute(httpPost, localContext); 
        HttpEntity resEntity = response.getEntity();

These are the libraries i used for this project,
post simulator

Hope it would help others, have fun (Y)


No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked

:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)