有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java URLConnection有时返回空字符串响应?

我正在发出http GET请求。它在我70%的尝试中都有效。由于某些原因,我有时无法从成功的连接中获得响应字符串。我只是在我的应用程序中设置了一个按钮,它会不断触发下面的代码。一个呼叫可能无法用字符串应答,下一个呼叫可以正常工作:

private onButtonClick() {
    try {
        doit();
    } catch (Exception ex) {
        ...
    }
}   

public void doit() throws Exception {
    URL url = new URL("http://www.example.com/service");

    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoInput(true);
    connection.setUseCaches(false); 
    connection.setAllowUserInteraction(false); 
    connection.setReadTimeout(30 * 1000);
    connection.setRequestProperty("Connection", "Keep-Alive"); 
    connection.setRequestProperty("Authorization", 
        "Basic " +  Base64.encode("username" + ":" + "password"));

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String line = "";
    StringBuilder sb = new StringBuilder();
    while ((line = in.readLine()) != null) {
        sb.append(line);
    }
    in.close();

    connection.disconnect();

    // Every so often this prints an empty string!
    System.out.println(sb.toString());
}

我做错什么了吗?似乎我没有从上次通话中正确地关闭连接,导致响应被破坏或是其他什么?我还同时从多个线程调用doit(),但我认为该方法的内容是线程安全的,尽管行为相同

谢谢

谢谢


共 (3) 个答案

  1. # 1 楼答案

    我们也遇到了类似的情况,我遇到了以下解决方案: -在URLConnection对象上设置用户代理字符串

    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)");
    

    more details

  2. # 2 楼答案

    这种方法看起来不错。它是可重入的,所以调用不应该相互干扰。这可能是服务器问题,或者是故意节流,或者只是一个bug

    编辑:您可以使用^{}检查状态代码

  3. # 3 楼答案

    要检查响应代码:

            BufferedReader responseStream;
            if (((HttpURLConnection) connection).getResponseCode() == 200) {
                responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            } else {
                responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
            }
    

    对于空内容,resposneCode为204。所以,若你们能得到一个空的身体,只需再加上一个204码的“若”