Java访问http/https方法

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

  有时候需要在Java后台去访问其他系统api,这些接口可能是http或https的。在网上搜索了下,还不少人提问,但是有些过于繁琐于是自己整理了一篇博客。

2、代码样例

  1、引入pom,版本一定要高一点的不然会报错。

1      <dependency>
2         <groupId>org.apache.httpcomponents</groupId>
3         <artifactId>httpclient</artifactId>
4         <version>4.5.3</version>
5     </dependency>

  2、代码例子

  1 package com.mao2080.util;
  2 
  3 import org.apache.http.HttpResponse;
  4 import org.apache.http.client.methods.HttpGet;
  5 import org.apache.http.client.methods.HttpPost;
  6 import org.apache.http.entity.StringEntity;
  7 import org.apache.http.impl.client.CloseableHttpClient;
  8 import org.apache.http.impl.client.HttpClients;
  9 import org.apache.http.util.EntityUtils;
 10 
 11 import java.util.HashMap;
 12 import java.util.Map;
 13 
 14 /**
 15  * HttpClient工具类
 16  */
 17 public class HttpClientUtil {
 18 
 19     /**请求编码*/
 20     private static final String DEFAULT_CHARSET = "UTF-8";
 21 
 22     /**
 23      * 执行HTTP POST请求
 24      * @param url url
 25      * @param param 参数
 26      * @return
 27      */
 28     public static String httpPostWithJSON(String url, Map<String, ?> param) {
 29         CloseableHttpClient client = null;
 30         try {
 31             if(url == null || url.trim().length() == 0){
 32                 throw new Exception("URL is null");
 33             }
 34             HttpPost httpPost = new HttpPost(url);
 35             client = HttpClients.createDefault();
 36             if(param != null){
 37                 StringEntity entity = new StringEntity(JSONUtils.toJSONString(param), DEFAULT_CHARSET);//解决中文乱码问题
 38                 entity.setContentEncoding(DEFAULT_CHARSET);
 39                 entity.setContentType("application/json");
 40                 httpPost.setEntity(entity);
 41             }
 42             HttpResponse resp = client.execute(httpPost);
 43             if(resp.getStatusLine().getStatusCode() == 200) {
 44                 return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
 45             }
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } finally {
 49             close(client);
 50         }
 51         return null;
 52     }
 53 
 54     /**
 55      * 执行HTTP GET请求
 56      * @param url url
 57      * @param param 参数
 58      * @return
 59      */
 60     public static String httpGetWithJSON(String url, Map<String, ?> param) {
 61         CloseableHttpClient client = null;
 62         try {
 63             if(url == null || url.trim().length() == 0){
 64                 throw new Exception("URL is null");
 65             }
 66             client = HttpClients.createDefault();
 67             if(param != null){
 68                 StringBuffer sb = new StringBuffer("?");
 69                 for (String key : param.keySet()){
 70                     sb.append(key).append("=").append(param.get(key)).append("&");
 71                 }
 72                 url = url.concat(sb.toString());
 73                 url = url.substring(0, url.length()-1);
 74             }
 75             HttpGet httpGet = new HttpGet(url);
 76             HttpResponse resp = client.execute(httpGet);
 77             if(resp.getStatusLine().getStatusCode() == 200) {
 78                 return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
 79             }
 80         } catch (Exception e) {
 81             e.printStackTrace();
 82         } finally {
 83             close(client);
 84         }
 85         return null;
 86     }
 87 
 88     /**
 89      * 关闭HTTP请求
 90      * @param client
 91      */
 92     private static void close(CloseableHttpClient client){
 93         if(client == null){
 94             return;
 95         }
 96         try {
 97             client.close();
 98         } catch (Exception e) {
 99         }
100     }
101 
102     public static void main(String[] args) throws Exception {
103         Map param = new HashMap();
104         param.put("userName", "admin");
105         param.put("password", "mao2080");
106         String result = httpGetWithJSON("https://www.baidu.com/", param);
107         System.out.println("result:"+result);
108     }
109 
110 
111 }

  3、运行结果

  

3、参考网站

  https://www.cnblogs.com/Vdiao/p/5339487.html

posted @ 2018-09-09 20:29  mao2080  阅读(22185)  评论(2)    收藏  举报