“java.lang.IllegalStateException:在建立连接后无法设置请求属性”在Android中出错

时间:2021-09-22 23:07:07

I am new to Android and trying to get HTML content of a web page and that is when I came across this issue.

我是Android的新手并试图获取网页的HTML内容,这就是我遇到这个问题的时候。

java.lang.IllegalStateException: Cannot set request property after connection is made

Code :

public static String getHTMLPage(String inputURL, String host, String referer, String cookie, String breakString) {

    String htmlContent = "";
    try {
        URL u = new URL(inputURL);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        uc.setRequestProperty("Host", host);
        uc.setRequestProperty("Connection", "keep-alive");
        if (!referer.isEmpty()) {
            uc.setRequestProperty("Referer", referer);
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1");
        uc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        uc.setRequestProperty("Accept-Encoding", "html");
        uc.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
        uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");

        if (!cookie.isEmpty()) {
            uc.setRequestProperty("Cookie", cookie);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            if (!breakString.isEmpty() && line.contains(breakString)) {
                break;
            }
            htmlContent += line;
        }
        br.close();
    } catch (Exception e) {
        System.out.println(e);
    }
    return htmlContent;
}

Basically, I have written this in a pure java application (where it is working fine) and I just wanted to re-use the same. I have googled and found few SO pages (1,2,3,4), but none of them addresses the problem specific to HTTPURLConnection directly. (Though, some advised about HTTPClient, which is found to be deprecated which I don't want to use.)

基本上,我已经在一个纯Java应用程序(它工作正常)中写了这个,我只是想重复使用它。我用google搜索并找到了几个SO页面(1,2,3,4),但它们都没有直接解决HTTPURLConnection特有的问题。 (虽然有些人建议使用HTTPClient,但我不想使用它。)

Adding getResponseCode() is returning the value as 200 successfully.

添加getResponseCode()会将值成功返回200。

System.out.println("RESPONSE CODE : "+uc.getResponseCode());

I have looked the reference page and which states

我查看了参考页面和哪些状态

public void setRequestProperty (String field, String newValue)

public void setRequestProperty(String field,String newValue)

Sets the value of the specified request header field. The value will only be used by the current URLConnection instance. This method can only be called before the connection is established.

设置指定的请求标头字段的值。该值仅由当前URLConnection实例使用。只能在建立连接之前调用此方法。

How I can set the request property before making the connections ? As per the code, we are getting the HTTPURLConnection object only after opening connection for a specific URL (and casting it with HTTPURLConnection)

如何在建立连接之前设置request属性?根据代码,我们只在打开特定URL的连接后(并使用HTTPURLConnection强制转换)获取HTTPURLConnection对象

         HttpURLConnection uc = (HttpURLConnection) u.openConnection();

What is the correct way to use HTTPURLConnection to read HTML page along with setRequestProperty ?

使用HTTPURLConnection与setRequestProperty一起阅读HTML页面的正确方法是什么?

1 个解决方案

#1


The connection isn't created by 'URL.openConnection().` It is created when you get the input or error stream or the response code.

连接不是由'URL.openConnection()创建的。它是在您获得输入或错误流或响应代码时创建的。

NB you shouldn't call setDoOutput(true) unless you are going to do output, which you aren't here. It sets the HTTP method to POST.

注意你不应该调用setDoOutput(true),除非你打算做输出,你不在这里。它将HTTP方法设置为POST。

#1


The connection isn't created by 'URL.openConnection().` It is created when you get the input or error stream or the response code.

连接不是由'URL.openConnection()创建的。它是在您获得输入或错误流或响应代码时创建的。

NB you shouldn't call setDoOutput(true) unless you are going to do output, which you aren't here. It sets the HTTP method to POST.

注意你不应该调用setDoOutput(true),除非你打算做输出,你不在这里。它将HTTP方法设置为POST。