1

I'm trying to read http://www.meuhumor.com.br/ on java using this:

URL url;
        HttpURLConnection connection = null;        
        try{
            url = new URL(targetURL);
            connection = (HttpURLConnection)url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Language", "en-US"); 
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.flush();
            dataout.close();

            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();

            while((line = br.readLine()) != null){
                response.append(line);
                response.append('\n');
            }
            br.close();
            String html = response.toString();

I can access the website using any browser, but when i try to get the html with Java im getting java.io.IOException: Server returned HTTP response code: 403 for URL:

Someone know a way to get the html?

4

1 回答 1

1

您很可能会收到 HTTP 403 响应,因为您的POST请求没有正文。您的代码看起来像是在尝试提交表单。如果您的意图是在不提交表单的情况下简单地下拉页面内容,请尝试GET请求,删除Content-Type标题,删除connection.setDoOutput(true),然后删除 3DataOutputStream行。

于 2012-08-22T01:13:34.613 回答