我正试图向
Java API文档关于URLConnection的说明: http://download.oracle.com/javase/6/docs/api/java/net/URLConnection.html Java教程中关于从URLConnection读取和写入的介绍: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html
URLConnection#getOutputStream
写入数据,但是在调用 URLConnection#getInputStream
之前并没有实际发送任何数据。即使我将 URLConnnection#doInput
设置为 false,它仍然不会发送数据。有人知道这是为什么吗?API文档中没有描述这一点。Java API文档关于URLConnection的说明: 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();
}
}
}
}