0
我試圖從API獲取數據通過HttpURLConnection類,但得到IOException,使用一個消息:HttpURLConnection類返回-1作爲響應代碼
Invalid Http response
然而,當我粘貼URL請求到瀏覽器我」以200作爲響應代碼得到正確的響應。這裏是代碼有什麼失敗:
public static String sendRequest(String url) throws IOException {
HttpURLConnection urlConnection = null;
String out = null;
System.setProperty("http.keepAlive", "false");
try {
URL serverAddress = new URL(url);
urlConnection = (HttpURLConnection) serverAddress.openConnection();
urlConnection.setReadTimeout(TIME_OUT_LENGTH);
urlConnection.setRequestMethod(REQUEST_METHOD_GET);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
out = Connection.readStream(in);
} catch (IOException e) {
System.out.println(e.getCause());
InputStream is = new BufferedInputStream(urlConnection.getErrorStream());
out = Connection.readStream(is);
} finally {
urlConnection.disconnect();
System.out.println(out);
return out;
}
}
private static String readStream(InputStream in) throws IOException {
String line;
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
while((line = r.readLine()) != null)
sb.append(line);
return sb.toString();
}
任何人看到我在做什麼錯?
---編輯----
堆棧跟蹤:
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1341)
at java.net.URL.openStream(URL.java:1037)
at com.urhola.cheddar.connection.Connection.sendRequest(Connection.java:33)
at com.urhola.cheddar.request.Request.execute(Request.java:63)
at com.urhola.cheddar.request.LineInformationRequest.execute(LineInformationRequest.java:36)
at tester.Client.main(Client.java:54)