zoukankan      html  css  js  c++  java
  • 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 请求出现异常!	请求ID:"+id+"
    "+e.getMessage()+"
    ");
    44         } finally {// 使用finally块来关闭输出流、输入流
    45             try {
    46                 if (in != null) {
    47                     in.close();
    48                 }
    49             } catch (IOException ex) {
    50                 logger.error("关闭数据流出错了!
    "+ex.getMessage()+"
    ");
    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

  • 相关阅读:
    danci8
    禁止选择文本
    danci6
    danci5
    java 学习编译
    自动代码模板文件
    java 学习5 .io
    java 学习4 callback 回调 和泛型
    java 学习3。集合
    java 学习3。类 和 继承
  • 原文地址:https://www.cnblogs.com/husky/p/6377577.html
Copyright © 2011-2022 走看看