Wednesday, April 28, 2010

HTTP Clent 4 HTTP PUT Multipart Client Code Sample

Few days back got stuck in usage of HTTP Client 4.0 Library usage for Multi Part Put Request.
Finally found a workaround and thought to share with everyone.

Below is the Sample code.


import java.io.File;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PutRequestTest {

public static void main(String[] args) {
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost method = new HttpPost("http://localhost:8080/AdamService/service/sharedshelf/json/insertImage");

File file = new File("/Users/imranlakhani/a.JPG");
MultipartEntity mp = new MultipartEntity();
mp.addPart("projectId", new StringBody("1234", Charset.forName("UTF-8")));
mp.addPart("Name", new StringBody("image.jpg", Charset.forName("UTF-8")));
mp.addPart("username", new StringBody("imran", Charset.forName("UTF-8")));
mp.addPart("instituteId", new StringBody("2", Charset.forName("UTF-8")));
mp.addPart("password", new StringBody("", Charset.forName("UTF-8")));
FileBody fileBody = new FileBody(file);
mp.addPart("File", fileBody);
method.setEntity(mp);

System.out.println("executing request " + method.getRequestLine());
HttpResponse response = httpclient.execute(method);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();

} catch (Exception e) {
e.printStackTrace();
}

}
}

3 comments:

Abhi said...

HI, CAN I KNOW HOW THE ADDPART WORKS..I AM UNABLE TO SEND PICTURES TO MY SERVER

Anonymous said...

Thanks for this, it was very useful!

Unknown said...

Thanks Everyone for your comments and feedback.