gpt4 book ai didi

java - 为什么必须调用 URLConnection#getInputStream 才能写出 URLConnection#getOutputStream?

转载 作者:IT老高 更新时间:2023-10-28 21:06:02 26 4
gpt4 key购买 nike

我正在尝试写信给 URLConnection#getOutputStream ,但是,在我调用 URLConnection#getInputStream 之前,实际上并没有发送任何数据。 .即使我设置URLConnnection#doInput为假,它仍然不会发送。有人知道为什么吗? API 文档中没有任何内容对此进行描述。

关于 URLConnection 的 Java API 文档:http://download.oracle.com/javase/6/docs/api/java/net/URLConnection.html

Java 关于读取和写入 URLConnection 的教程:http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class UrlConnectionTest {

private static final String TEST_URL = "http://localhost:3000/test/hitme";

public static void main(String[] args) throws IOException {

URLConnection urlCon = null;
URL url = null;
OutputStreamWriter osw = null;

try {
url = new URL(TEST_URL);
urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setRequestProperty("Content-Type", "text/plain");

////////////////////////////////////////
// SETTING THIS TO FALSE DOES NOTHING //
////////////////////////////////////////
// urlCon.setDoInput(false);

osw = new OutputStreamWriter(urlCon.getOutputStream());
osw.write("HELLO WORLD");
osw.flush();

/////////////////////////////////////////////////
// MUST CALL THIS OTHERWISE WILL NOT WRITE OUT //
/////////////////////////////////////////////////
urlCon.getInputStream();

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// If getInputStream is called while doInput=false, the following exception is thrown: //
// java.net.ProtocolException: Cannot read from URLConnection if doInput=false (call setDoInput(true)) //
/////////////////////////////////////////////////////////////////////////////////////////////////////////

} catch (Exception e) {
e.printStackTrace();
} finally {
if (osw != null) {
osw.close();
}
}

}

}

最佳答案

用于 URLConnection 和 HttpURLConnection 的 API(无论好坏)是为用户设计的,以遵循非常特定的事件序列:

  1. 设置请求属性
  2. (可选)getOutputStream(),写入流,关闭流
  3. getInputStream(),从流中读取,关闭流

如果您的请求是 POST 或 PUT,则需要可选步骤 #2。

据我所知,OutputStream 不像套接字,它不直接连接到服务器上的 InputStream。相反,在您关闭或刷新流并调用 getInputStream() 后,您的输出将内置到请求中并发送。语义基于您将要阅读响应的假设。我看到的每个示例都显示了这种事件顺序。我当然同意你和其他人的观点,即这个 API 与普通的流 I/O API 相比是违反直觉的。

tutorial您链接到“URLConnection 是一个以 HTTP 为中心的类”的状态。我将其解释为这些方法是围绕请求-响应模型设计的,并假设它们将如何使用。

对于它的值(value),我找到了 bug report这比 javadoc 文档更好地解释了该类的预期操作。报告的评估表明“发出请求的唯一方法是调用 getInputStream。”

关于java - 为什么必须调用 URLConnection#getInputStream 才能写出 URLConnection#getOutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com