如何使用HttpUrlConnection在POST请求中发送requestparameter

时间:2011-05-02 16:28:34

标签: java http-post

我需要向URL发送POST请求并发送一些请求参数。我正在使用HttpURLConnectionAPI。但我的问题是我在servlet中没有得到任何请求参数。虽然我看到params存在于请求体中,但是当我使用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();

2 个答案:

答案 0 :(得分:2)

为了更清洁,您可以编码以发送值。

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

答案 1 :(得分:0)

就像@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);