&引用;java.lang.IllegalStateException:建立连接后无法设置请求属性";Android中的错误

&引用;java.lang.IllegalStateException:建立连接后无法设置请求属性";Android中的错误,java,android,httpurlconnection,Java,Android,Httpurlconnection,我是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) {

我是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应用程序中编写的(它工作得很好),我只是想重复使用它。我在谷歌上搜索了几页(,,),但没有一页直接解决了
HTTPURLConnection
的问题。(不过,有些人建议使用
HTTPClient
,但发现它已被弃用,我不想使用。)

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

System.out.println("RESPONSE CODE : "+uc.getResponseCode());
我已经看了这一页,哪些是国家

公共void setRequestProperty(字符串字段,字符串newValue)

设置指定请求标头字段的值。价值将 只能由当前URLConnection实例使用。这种方法可以 只能在建立连接之前调用

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


使用
HTTPURLConnection
阅读HTML页面以及
setRequestProperty
的正确方法是什么

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


注意:您不应该调用
setDoOutput(true)
,除非您要执行输出,而您不在这里。它将HTTP方法设置为POST。

@EJP:Without
setDoOutput
也是同样的问题。我在这里发布时忘记删除这些行。@EJP:BTW,如果连接不是由
openConnection()
方法创建的,那么为什么它会抛出错误,因为在建立连接后
无法设置请求属性
?我还需要做些什么才能让它工作?@Dinesh它没有,用你发布的代码。您一定调用了其他打开连接的程序。看见
         HttpURLConnection uc = (HttpURLConnection) u.openConnection();