Wednesday, April 22, 2009

Upload a file to another webpage through a Java Servlet

In past few days, I had to work on implementing a functionality for sending an HTTP request to another url and upload a file with that HTTP request and then get the response for the HTTP request from a Java servlet. This is the code I finally created for achieving my task. It does,
  1. Connect to another given URL
  2. Upload given string as a file to the above url
  3. Then read the response for the above HTTP request.
Below function is called inside the protected void processRequest(HttpServletRequest request, HttpServletResponse response) of a Servlet in my project. I have put the relevant code for achieving this task in below.

// Import these packages

// Code
private String uploadFile(String urlstring, String dataXML) {
try {
 String itemname = "formFile"; String tempfilename = "test.xml";  String lineEnd = "\r\n";  String twoHyphens = "--";
 String boundary = "---------------------------24464570528145";
 URL url = new URL(urlstring);
 HttpURLConnection connection = (HttpURLConnection)  url.openConnection();



 connection.setRequestProperty("Connection", "keep-alive"); 

 connection.setRequestProperty("Content-Type", "multipart/form- data; boundary=" + boundary);
 connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

 DataOutputStream dataoutputstream = new          


 dataoutputstream.writeBytes(twoHyphens + boundary + lineEnd);

 dataoutputstream.writeBytes("Content-Disposition: form-data;    name=\"" + itemname + "\"; filename=\"" + tempfilename + "\"" +  lineEnd);

 dataoutputstream.writeBytes("Content-Type: text/plain" +  lineEnd + lineEnd);
 // dataXML is File data, writes a string as the file content of  the uploading
 // file

 dataoutputstream.writeBytes(twoHyphens + boundary + twoHyphens +


 String inputLine;
 StringBuffer sbResponseData = new StringBuffer();

 // Get the response data for the previous HTTP request

 DataInputStream dis = new  DataInputStream(connection.getInputStream());
 while ((inputLine = dis.readLine()) != null) {
  sbResponseData.append(inputLine + "\n");

 return sbResponseData.toString();

 catch (Exception ex) {
  logger.error("Exception in initiating outdial call request:       Details: " + ex.toString());



No comments: