Tôi đang cố viết ra URLConnection#getOutputStream
, tuy nhiên, không có dữ liệu nào thực sự được gửi cho đến khi tôi gọi URLConnection#getInputStream
. Ngay cả khi tôi đặt URLConnnection#doInput
thành sai, nó vẫn sẽ không gửi. Có ai biết tại sao điều này? Không có gì trong tài liệu API mô tả điều này.Tại sao bạn phải gọi URLConnection # getInputStream để có thể ghi ra URLConnection # getOutputStream?
Java API Documentation trên URLConnection: http://download.oracle.com/javase/6/docs/api/java/net/URLConnection.html
Java Hướng dẫn về đọc và ghi vào một 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();
}
}
}
}
Tìm tốt trên lỗi! Điều đó thực sự rõ ràng mọi thứ và tôi vui mừng khi biết rằng nó đã được ghi lại ở đâu đó. Cảm ơn! – John
Java 8 vẫn có lỗi này/tính năng không có giấy tờ, như tôi vừa mới phát hiện ra. (Tôi tìm thấy trang này trong khi tìm kiếm một giải pháp hoặc giải pháp cho vấn đề này.) Có một lựa chọn tốt hơn bây giờ, hơn sáu năm sau khi câu hỏi ban đầu đã được yêu cầu? –