在Android中出现"java.lang.IllegalStateException: Cannot set request property after connection is made"错误

3
我是Android新手,试图获取网页的HTML内容,但遇到了这个问题。
java.lang.IllegalStateException: Cannot set request property after connection is made

代码:

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;
}

基本上,我已经用纯 java 应用程序编写了这个程序(在那里它运行正常),我只想重复使用它。我已经搜索并找到了一些 SO 页面(1234),但没有一个直接解决与 HTTPURLConnection 相关的问题。(尽管有些人建议使用 HTTPClient,但我不想使用它,因为它已被弃用。)添加 getResponseCode() 会成功返回值为 200。
System.out.println("RESPONSE CODE : "+uc.getResponseCode());

我已查看reference页面,其中说明: public void setRequestProperty (String field, String newValue) 设置指定请求头字段的值。该值仅由当前的URLConnection实例使用。此方法只能在建立连接之前调用。
那么如何在建立连接之前设置请求属性?根据代码,我们只有在打开特定URL的连接并将其转换为HTTPURLConnection后才能获取HTTPURLConnection对象。
         HttpURLConnection uc = (HttpURLConnection) u.openConnection();

什么是使用 HTTPURLConnectionsetRequestProperty 正确读取 HTML 页面的方法?
1个回答

1
连接不是由'URL.openConnection()创建的。它是在获取输入或错误流或响应代码时创建的。
注意,除非您要进行输出,否则不应调用setDoOutput(true)。它将HTTP方法设置为POST。

@ EJP: 没有setDoOutput,同样的问题。我在发布这里时忘记删除那些行了。 - Dinesh
@ EJP:顺便提一句,如果连接不是通过openConnection()方法创建的,那么为什么会抛出“无法设置请求属性,因为连接已经建立”的错误?我还需要做什么才能使它工作? - Dinesh
@Dinesh,根据您发布的代码来看,并没有打开连接。您可能调用了其他方法来打开连接。请参考这里 - user207421

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接