【问题标题】:How to send requestparameter in POST request using HttpUrlConnection如何使用 HttpUrlConnection 在 POST 请求中发送请求参数
【发布时间】:2013-02-21 13:31:12
【问题描述】:

我需要向 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();

【问题讨论】:

  • 不确定是否需要在参数字符串中使用前导 &。另外,你应该 writer.write(params.getBytes())

标签: java http-post


【解决方案1】:

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

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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 2014-12-06
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 2018-12-14
      相关资源
      最近更新 更多