1

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

1 回答 1

0

好的,我切换到Apaches HTTP 客户端,它抛出一个异常,说 url 参数无效。所以我检查并注意到我正在发送一个参数(通常包括空格)而没有编码它们。在编码参数(下面的例子)之后,一切都很顺利。

URLEncoder.encode(parameter, "UTF-8");
于 2013-09-29T02:55:43.280 回答