是否可以对某些URL执行POST方法请求并避免阅读响应?
无论我多么努力地避免阅读响应,除非我读取响应,否则数据似乎永远不会到达服务器......奇怪吗?
我真的没有必要阅读任何回复数据,因为我将要做的就是发布数据..(无论如何响应总是空白的)
URL postURL = new URL("http://www.example.com/test/");
HttpURLConnection con = (HttpURLConnection) postURL.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(false); //why even make this if it doesn't function?
con.setRequestMethod("POST");
//PrintWriter out = new PrintWriter(con.getOutputStream());
OutputStream out = con.getOutputStream();
byte[] /*String postStr*/ bPost = ("foo1="+URLEncoder.encode("bar1")+"&"+
"foo2="+URLEncoder.encode("bar2")+"&"+
"foo3="+URLEncoder.encode("bar3").getBytes();
out.write(bPost);
//out.println(postStr); // send to server
out.flush();
out.close(); // close outputstream
//con.getInputStream().close(); //thought maybe this would help but no change.
/*
//If I uncomment this it will work.
String inputLine=""; //Stores the line of text returned by the server
String resultsPage=""; // Stores the complete HTML results page
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
while ((inputLine = in.readLine()) != null)
resultsPage+=inputLine;
in.close();
*/
答案 0 :(得分:3)
写入后调用getResponseCode()
。
这也会为您提供404作为响应代码,而不是FileNotFoundException
。
答案 1 :(得分:-1)
您是否尝试过调用con.connect()
?
否则它可能会“懒得”,当它绝对必须(POST缓冲区已满,开始读取响应头等)。