java 如何使用 HttpUrlConnection 在 POST 请求中发送请求参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5859667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:09:11  来源:igfitidea点击:

How to send requestparameter in POST request using HttpUrlConnection

javahttp-post

提问by deepak mishra

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?

我需要向 URL 发送 POST 请求并发送一些请求参数。我为此使用了 HttpURLConnectionAPI。但我的问题是我没有在 servlet 中得到任何请求参数。虽然我看到请求正文中存在参数,但当我使用 request.getReader 打印请求正文时。以下是客户端代码。任何机构都可以指定这是否是在 POST 请求中发送请求参数的正确方法?

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

回答by muruga

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

回答by Femi

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

就像@Kal 所说的那样,去掉前导&,不要理会 BufferedWriter。这对我有用:

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