![](/img/trans.png)
[英]server returns java.io.IOException: Server returned HTTP response code: 400 for URL
[英]Server returned HTTP response code: 400 for URL : java.io.IOException
我究竟做錯了什么? 請看一下代碼。
HttpURLConnection conn = (HttpURLConnection) new URL(http_url).openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
/*
java.io.IOException: Server returned HTTP response code: 400 for URL: http_url
at sun.net.www.protocol.http.HttpURLConnection.getInputStream
*/
如果我在瀏覽器中打開http_url,它就可以正常工作。
您沒有連接(來自http://alvinalexander.com/blog/post/java/how-open-url-read-contents-httpurl-connection-java的下一個代碼)。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// uncomment this if you want to write output to this url
//connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
因為我收到了Java錯誤而不是錯誤負載,所以我感到困惑。 稍后,當我在郵遞員中檢查http_url時,它顯示了錯誤的有效負載以及響應代碼400。如果有效負載可用,瀏覽器將不顯示響應代碼。 實際上,如果響應代碼> = 400,我應該使用conn.getErrorStream()
代替conn.getInputStream()
。
您必須遵循HTTP協議,並設置服務器期望在讀取響應之前獲得的所有HTTP標頭。 肯定您錯過了一個或多個標頭,例如content-type,accept等。也可能服務器不喜歡Java代理標頭,並且喜歡IE,Chrome,Firefox等的代理。所以服務器是正確的,您的請求很糟糕:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.