HttpURLConnection返回-1作为响应代码

时间:2013-09-28 12:05:45

标签: java httpurlconnection http-status-codes

我正在尝试通过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)

1 个答案:

答案 0 :(得分:0)

好的,我切换到Apaches HTTP client并且它抛出了一个异常,说url参数无效。所以我检查并注意到我发送的参数(通常包括空格)没有编码。编码参数(例如下面的代码)后,一切都运行得很好。

URLEncoder.encode(parameter, "UTF-8");