java網絡爬蟲,亂碼問題終於完美解決


第一次寫爬蟲,被亂碼問題困擾兩天,試了很多方法都不可以,今天隨便一試,居然好了。

在獲取網頁時創建了一個緩沖字節輸入流,問題就在這個流上,添加標紅代碼即可

BufferedReader in = null;

in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));

附上代碼,以供參考。

 1 public String sendGet(String url) {
 2         Writer write = null;
 3         // 定義一個字符串用來存儲網頁內容
 4         String result = null;
 5         // 定義一個緩沖字符輸入流
 6         BufferedReader in = null;
 7         try {
 8             // 將string轉成url對象
 9             URL realUrl = new URL(url);
10             // 初始化一個鏈接到那個url的連接
11             URLConnection connection = realUrl.openConnection();
12             // 開始實際的連接
13             connection.connect();
14             // 初始化 BufferedReader輸入流來讀取URL的響應
15             in = new BufferedReader(new InputStreamReader(
16                     connection.getInputStream(),"utf-8"));
17             // 用來臨時存儲抓取到的每一行的數據
18             String line;
19 
20             File file = new File(saveEssayUrl, fileName);
21             File file2 = new File(saveEssayUrl);
22 
23             if (file2.isDirectory() == false) {
24                 file2.mkdirs();
25                 try {
26                     file.createNewFile();
27                     System.out.println("********************");
28                     System.out.println("創建" + fileName + "文件成功!!");
29 
30                 } catch (IOException e) {
31                     e.printStackTrace();
32                 }
33 
34             } else {
35                 try {
36                     file.createNewFile();
37                     System.out.println("********************");
38                     System.out.println("創建" + fileName + "文件成功!!");
39                 } catch (IOException e) {
40                     e.printStackTrace();
41                 }
42             }
43             Writer w = new FileWriter(file);
44             
45             while ((line = in.readLine()) != null) {
46                 // 遍歷抓取到的每一行並將其存儲到result里面
47 //                line = new String(line.getBytes("utf-8"),"gbk");
48                 w.write(line);
49                 w.write("\r\n");
50                 result += line;
51             }
52             w.close();
53         } catch (Exception e) {
54             System.out.println("發送GET請求出現異常!" + e);
55             e.printStackTrace();
56         }
57         // 使用finally來關閉輸入流
58         finally {
59             try {
60                 if (in != null) {
61                     in.close();
62                 }
63                 
64             } catch (Exception e2) {
65                 e2.printStackTrace();
66             }
67         }
68         return result;
69     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM