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

posted @ 2017-02-08 12:00  时光舟  阅读(2875)  评论(0编辑  收藏  举报