How to send requestparameter in POST request using HttpUrlConnection

馋奶兔 提交于 2020-01-16 00:54:11

问题


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:


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);



回答2:


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);


来源:https://stackoverflow.com/questions/5859667/how-to-send-requestparameter-in-post-request-using-httpurlconnection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!