解決:java 抓取網站內容---403(禁止訪問代號)

     實現抓取網站內容源碼:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebPageSource {
    public static void main(String args[]){    
        URL url;
        int responsecode;
        HttpURLConnection urlConnection=null;
        BufferedReader reader=null;
        String line;
        try{
            //生成一個URL對象,要獲取源代碼的網頁地址爲:http://www.sina.com.cn
            url=new URL("http://www.sina.com.cn");
            //打開URL
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); //防止報403錯誤。
            //獲取服務器響應代碼
            responsecode=urlConnection.getResponseCode();
            if(responsecode==200){
                //得到輸入流,即獲得了網頁的內容 
                   reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
               while((line=reader.readLine())!=null){
                    System.out.println(line);
                }
         
            }
            else{
                System.out.println("獲取不到網頁的源碼,服務器響應代碼爲:"+responsecode);
            }
        }
        catch(Exception e){
            System.out.println("獲取不到網頁的源碼,出現異常:"+e);
        }
          finally{
              try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            urlConnection.disconnect();
        }
      }
    }
}

附加:

    HTTP 403命令是禁止惡意訪問此網站,不能從此網站中抓取內容。    如果是服務器端禁止抓取,那麼這個你可以通過設置User-Agent來欺騙服務器.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章