HTTP-java模擬Get請求小栗子


 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 import java.net.HttpURLConnection;
 5 import java.net.URL;
 6  8 import javax.net.ssl.HttpsURLConnection;10 
11 import org.apache.log4j.Logger;13 16 /*
17  * GET請求類,非線程類
18  */
19 public class GetRequest {
20     private String url = "https://b2b.10086.cn/b2b/main/viewNoticeContent.html?noticeBean.id=";
21     private Logger logger;
22     public GetRequest() {
23         logger = Logger.getLogger(GetRequest.class);
24     }
25 
26     public ExtendCandidate getData(String id) {
27         this.url = url + id;
28         BufferedReader in = null;
29         HttpURLConnection conn = null;
30         String result = "";
31         try {
32             conn = (HttpURLConnection)new URL(url).openConnection();
33             // 發送GET請求必須設置如下兩行
34             conn.setDoInput(true);
35             conn.setRequestMethod("GET");
36             // flush輸出流的緩沖
37             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
38             String line;
39             while ((line = in.readLine()) != null) {
40                 result += line;
41             }
42         } catch (Exception e) {
43             logger.error("發送 GET 請求出現異常!\t請求ID:"+id+"\n"+e.getMessage()+"\n");
44         } finally {// 使用finally塊來關閉輸出流、輸入流
45             try {
46                 if (in != null) {
47                     in.close();
48                 }
49             } catch (IOException ex) {
50                 logger.error("關閉數據流出錯了!\n"+ex.getMessage()+"\n");
51             }
52         }
53         //獲取到結果result,可以直接添加處理,或者存儲到全局變量......
54     }
55 }

相關文章:

  java模擬Post請求: http://www.cnblogs.com/husky/p/6377553.html

    java https請求忽略安全證書信任: http://www.cnblogs.com/husky/p/6378290.html


免責聲明!

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



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