zoukankan      html  css  js  c++  java
  • java发http请求

    下面介绍两种方式 
    1.使用jdk提供的URLConnection 
    2.使用apache提供的HttpClient(封装了jdk)

    一、使用URLConnect进行http请求

      1 public class HttpUtil {
      2 
      3     /**
      4      * 向指定URL发送GET方法的请求
      5      *
      6      * @param url
      7      *            发送请求的URL
      8      * @param param
      9      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     10      * @return URL 所代表远程资源的响应结果
     11      */
     12     public static String sendGet(String url, String param) {
     13         String result = "";
     14         BufferedReader in = null;
     15         try {
     16             String urlNameString = url + "?" + param;
     17             URL realUrl = new URL(urlNameString);
     18             // 打开和URL之间的连接
     19             URLConnection connection = realUrl.openConnection();
     20             // 设置通用的请求属性
     21             connection.setRequestProperty("accept", "*/*");
     22             connection.setRequestProperty("connection", "Keep-Alive");
     23             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
     24             // 建立实际的连接
     25             connection.connect();
     26             // 获取所有响应头字段
     27             Map<String, List<String>> map = connection.getHeaderFields();
     28             // 遍历所有的响应头字段
     29             for (String key : map.keySet()) {
     30                 System.out.println(key + "--->" + map.get(key));
     31             }
     32             // 定义 BufferedReader输入流来读取URL的响应
     33             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     34             String line;
     35             while ((line = in.readLine()) != null) {
     36                 result += line;
     37             }
     38         } catch (Exception e) {
     39             System.out.println("发送GET请求出现异常!" + e);
     40             e.printStackTrace();
     41         }
     42         // 使用finally块来关闭输入流
     43         finally {
     44             try {
     45                 if (in != null) {
     46                     in.close();
     47                 }
     48             } catch (Exception e2) {
     49                 e2.printStackTrace();
     50             }
     51         }
     52         return result;
     53     }
     54 
     55     /**
     56      * 向指定 URL 发送POST方法的请求
     57      *
     58      * @param url
     59      *            发送请求的 URL
     60      * @param param
     61      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     62      * @return 所代表远程资源的响应结果
     63      */
     64     public static String sendPost(String url, String param) {
     65         PrintWriter out = null;
     66         BufferedReader in = null;
     67         String result = "";
     68         try {
     69             URL realUrl = new URL(url);
     70             // 打开和URL之间的连接
     71             URLConnection conn = realUrl.openConnection();
     72             // 设置通用的请求属性
     73             conn.setRequestProperty("accept", "*/*");
     74             conn.setRequestProperty("connection", "Keep-Alive");
     75             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
     76             // 发送POST请求必须设置如下两行
     77             conn.setDoOutput(true);
     78             conn.setDoInput(true);
     79             // 获取URLConnection对象对应的输出流
     80             out = new PrintWriter(conn.getOutputStream());
     81             // 发送请求参数
     82             out.print(param);
     83             // flush输出流的缓冲
     84             out.flush();
     85             // 定义BufferedReader输入流来读取URL的响应
     86             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     87             String line;
     88             while ((line = in.readLine()) != null) {
     89                 result += line;
     90             }
     91         } catch (Exception e) {
     92             System.out.println("发送 POST 请求出现异常!" + e);
     93             e.printStackTrace();
     94         }
     95         // 使用finally块来关闭输出流、输入流
     96         finally {
     97             try {
     98                 if (out != null) {
     99                     out.close();
    100                 }
    101                 if (in != null) {
    102                     in.close();
    103                 }
    104             } catch (IOException ex) {
    105                 ex.printStackTrace();
    106             }
    107         }
    108         return result;
    109     }
    110 
    111     public static void main(String[] args) {
    112         // 发送 GET 请求
    113         String result = HttpUtil.sendGet("http://baidu.com", "key=123&v=456");
    114         System.out.println("result: " + result);
    115         System.out.println("-----------------------------------------------------");
    116         // 发送 POST 请求
    117         String sr = HttpUtil.sendPost("http://baidu.com", "key=123&v=456");
    118         System.out.println("sr: " + sr);
    119     }
    120 }

    二、使用HttpClient进行http请求

    maven依赖:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    代码:

    public class HttpClientUtil {
        public static void get() {
            /**
             * client和response需要关闭资源
             */
            // 创建client,放入try()中自动释放,不需要finally
            try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
    
                // 执行得到response
                try (CloseableHttpResponse response = client.execute(new HttpGet("http://www.baidu.com"))) {
                    // 获取statusCode
                    Integer statusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        // body
                        String bodyAsString = EntityUtils.toString(entity);
                        // Media Type
                        String contentMimeType = ContentType.getOrDefault(entity).getMimeType();
                        // head
                        Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
                        // 输出
                        System.out.println("statusCode:" + statusCode);
                        System.out.println("contentMinmeType:" + contentMimeType);
                        System.out.println("body:" + bodyAsString);
                        System.out.println("head" + headers);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static void post() {
            // 创建client
            try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
                HttpPost postRequest = new HttpPost("http://www.baidu.com");
                // 添加请求参数
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("key1", "value1"));
                params.add(new BasicNameValuePair("key2", "value2"));
                postRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
                // 执行并获取返回结果到response
                try (CloseableHttpResponse response = client.execute(postRequest)) {
                    // 获取statusCode
                    Integer statusCode = response.getStatusLine().getStatusCode();
                    // Media Type
                    String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
                    // body
                    String bodyAsString = EntityUtils.toString(response.getEntity());
                    // head
                    Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
                    System.out.println("statusCode:" + statusCode);
                    System.out.println("contentMinmeType:" + contentMimeType);
                    System.out.println("body:" + bodyAsString);
                    System.out.println("head" + headers);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            get();
            System.out.println("------------------------------------");
            post();
        }
    }

    转载:

    https://blog.csdn.net/ludonglue/article/details/78038643

  • 相关阅读:
    springMVC之配置
    compareTo(String str)与compareToIgnoreCase(String str)
    js中的json
    Java转json
    mxnet 豆瓣镜像源安装
    查看 tensorflow 是GPU版本 还是CPU版本
    nvidia-docker安装
    ubuntu下安装tensorflow-gpu版本过程
    CUDA, CUDNN 版本查询
    ubuntu版本查看命令
  • 原文地址:https://www.cnblogs.com/step-and-step/p/9348527.html
Copyright © 2011-2022 走看看