【问题标题】:Why do I need getInputStream for HttpUrlConnection to send request?为什么我需要 getInputStream 才能让 HttpUrlConnection 发送请求?
【发布时间】:2013-02-17 07:11:23
【问题描述】:

我有一些代码可以从 Java 小程序向 PHP 脚本发送 POST 请求:

String message = URLEncoder.encode(s, "UTF-8");
URL url = new URL(getCodeBase(), "script.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("message=" + message);
out.close();

但这在发送请求时不起作用。我必须添加调用 getInputStream() 的代码并读取所有输入才能使其工作。为什么是这样?如果我只想发送请求而不接收请求怎么办?

【问题讨论】:

    标签: java post applet request httpurlconnection


    【解决方案1】:

    您不需要,但您必须致电 getInputStream()getResponseCode()。否则不会发送任何内容,否则您将无法知道调用是否成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2020-08-17
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多