1

I need to send a POST request to a URL and send some request parameters. I am using HttpURLConnectionAPI for this. But my problem is I do not get any request parameter in the servlet. Although I see that the params are present in the request body, when I print the request body using request.getReader. Following is the client side code. Can any body please specify if this is correct way to send request parameters in POST request?

String urlstr = "http://serverAddress/webappname/TestServlet";

String params = "&paramname=paramvalue";

URL url = new URL(urlstr);

HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();

urlconn.setDoInput(true);

urlconn.setDoOutput(true);

urlconn.setRequestMethod("POST");

urlconn.setRequestProperty("Content-Type", "text/xml");

urlconn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));

urlconn.setRequestProperty("Content-Language", "en-US");

OutputStream os = urlconn.getOutputStream();

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

writer.write(params);

writer.close();

os.close();
1
  • Not sure if you need that leading & in your params string. Also, you should writer.write(params.getBytes()) Commented May 2, 2011 at 16:40

2 Answers 2

2

To be cleaner, you can encode to send the values.

String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

URL url = new URL("http://yourserver.com/whatever");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
Sign up to request clarification or add additional context in comments.

Comments

0

Like @Kal said, get rid of the leading & and don't bother with the BufferedWriter. This works for me:

byte[] bytes = parameters.getBytes("UTF-8");
httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.connect();
outputStream = httpUrlConnection.getOutputStream();
outputStream.write(bytes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.