Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

HttpClient File Upload

807588Apr 22 2009 — edited Apr 22 2009
Hi,

I have a problem uploading a file using HttpClient from Apache.
Here is the scenario:

I have a simple Java Servlet rendering a form having three fields:
1. Text Box
2. Text Box
3. File
This form has POST method.

I want to write a piece of Java code to submit the POST request.
I tried using the HttpClient and PostMethod. That doesn't seem to
work in my case.

Here is the servlet code:

response.setContentType("text/html");

PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");

String title = rb.getString("requestparams.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");

// img stuff not req'd for source code html showing

// all links relative

// XXX
// making these absolute till we work out the
// addition of a PathInfo issue

out.println("<a href=\"../reqparams.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");

out.println("<h3>" + title + "</h3>");
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
Object file = (Object)request.getParameter("upfile");
out.println(rb.getString("requestparams.params-in-req") + "<br>");
if (firstName != null || lastName != null) {
out.println(rb.getString("requestparams.firstname"));
out.println(" = " + HTMLFilter.filter(firstName) + "<br>");
out.println(rb.getString("requestparams.lastname"));
out.println(" = " + HTMLFilter.filter(lastName));
out.println("File: ");
out.println(" = " + HTMLFilter.filter(file.toString()));

} else {
out.println(rb.getString("requestparams.no-params"));
}
out.println("<P>");
out.print("<form action=\"");
out.print("RequestParamExample\" ");
out.println("method=POST>");
out.println(rb.getString("requestparams.firstname"));
out.println("<input type=text size=20 name=firstname>");
out.println("<br>");
out.println(rb.getString("requestparams.lastname"));
out.println("<input type=text size=20 name=lastname>");
out.println("<br>");
out.println("File: ");
out.println("<input type=file name=upfile>");
out.println("<input type=submit>");
out.println("</form>");

out.println("</body>");
out.println("</html>");

Here is the java code I wrote using HttpClient and PostMethod

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.FilePartSource;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class ParamTest {

public static void main(String[] args) {
HttpClient client = new HttpClient();
BufferedReader br = null;

PostMethod postMethod = new PostMethod("http://localhost:8080/servlets-examples/servlet/RequestParamExample");
postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,true);

File f = new File("HostProfile3112009_1354502.log");
try {
Part[] parts = {
new StringPart("firstname", "Praveen"),
new StringPart("lastname", "Yarlagadda"),
new FilePart(f.getName(), f)
};

postMethod.setRequestEntity(
new MultipartRequestEntity(parts, postMethod.getParams())
);
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
}

client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

try{
int returnCode = client.executeMethod(postMethod);

if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
postMethod.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
String readLine;
while(((readLine = br.readLine()) != null)) {
System.err.println(readLine);
}
}
} catch (Exception e) {
System.err.println(e);
} finally {
postMethod.releaseConnection();
if(br != null) try { br.close(); } catch (Exception fe) {}
}
}
}

It is supposed to create a POST request and send it to the Server. But,
I don't think the server is receiving the POST request containing all the data.
As a result, I receive only Servlet content, not the content it generates after
receiving the POST request. If anybody knows what is wrong with this,
please help. If I am using the wrong APIs, please let me know.

Thank you,
Praveen
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 20 2009
Added on Apr 22 2009
2 comments
316 views