[英]HttpURLConnection returns -1 as a response code
I'm trying to fetch data from an API via HttpURLConnection but getting IOException with a message: 我正在尝试通过HttpURLConnection从API中获取数据,但出现IOException消息:
Invalid Http response
However, when I paste the request url to the browser I'm getting the correct response with 200 as a response code. 但是,当我将请求URL粘贴到浏览器时,我得到了正确的响应,并带有200作为响应代码。 Here's the code what's failing:
这是失败的代码:
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();
}
Anyone seeing what I'm doing wrong? 有人看到我在做什么错吗?
--- EDIT ---- -编辑-
Stack trace: 堆栈跟踪:
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)
Okay, I switched to Apaches HTTP client and it threw an exception saying url parameters were invalid. 好的,我切换到Apache的HTTP客户端 ,它抛出一个异常,指出url参数无效。 So I checked and noticed I was sending a parameters (which often included spaces) without encoding them.
因此,我检查并注意到我在发送参数(通常包含空格)而不对它们进行编码。 After encoding parameters (example below) everything worked beautifully.
在对参数进行编码(下面的示例)之后,一切工作正常。
URLEncoder.encode(parameter, "UTF-8");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.