我正在尝试通过 HttpURLConnection 从 API 获取数据,但收到 IOException 并显示一条消息:
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)