HttpClient基础学习

参考文章:https://blog.csdn.net/qq_28165595/article/details/78885775

                 https://blog.csdn.net/sinat_32759831/article/details/79705851

                https://blog.csdn.net/cloud_july/article/details/73301805

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

一、GET请求方式

1. 创建HttpClient实例。

2. 创建HttpGet请求方法实例,如果有带请求参数,需要地址和参数进行拼接,作为HttpGet的参数。

拼接的方法,首先将请求参数以键和值的形式封装到NameValuePair实例中,将实例存放到List集合中,通过UrlEncodedFormEntity(list,charset)编码成合适的格式,使用EntityUtils转换成字符串格式后与请求地址进行拼接。

3. 执行HttpGet实例,得到应答结果,从应答结果中可以获取应答行,应答消息体等。

4. 释放连接。

public class HttpSample {
    public static void main(String[] args) throws IOException {
        String url = "http://www.baidu.com";
        Map<String, String> map = new HashMap();
        String charset = "utf-8";
        doGet(url, map, charset);
    }

    public static String doGet(String url, Map<String, String> params, String charset) throws IOException {
        if (StringUtils.isBlank(url)) {//使用isBlank()判断字符串是否为null,""," "三种情况
            return null;
        }
        url = urlConnection(url,params,charset);//url和请求参数拼接
        CloseableHttpClient client = HttpClients.createDefault();//创建HttpClient实例
        HttpGet httpGet = new HttpGet("http://www.baidu.com");//创建GET请求实例
        CloseableHttpResponse response = client.execute(httpGet);//执行请求
        StatusLine line = response.getStatusLine();//获取整个应答行
        String version = line.getProtocolVersion().toString();//获取应答行的协议版本
        int statusCode = line.getStatusCode();//获取应答行的状态码
        String s = line.getReasonPhrase();//获取应答行的状态描述
         System.out.println(line.toString());//打印应答行
        System.out.println(version + ":" + statusCode + ":" + s);//打印应答行
        HttpEntity entity = response.getEntity();//获取返回消息实体
        System.out.println(EntityUtils.toString(entity, "utf-8"));//打印消息实体,
        response.close();//释放连接
        return line.toString();
    }
     //地址拼接方法
     public static String urlConnection(String url,Map<String,String> params,String charset) throws IOException {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> list = new ArrayList<>();//用于存放请求参数实例,请求参数封装到NameValuePair实例中
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                if (value != null) {
                    list.add(new BasicNameValuePair(key, value));
                }
            }
            //BasicNameValuePair中的键值对,被UrlEncodedFormEntity实例编码后变为:param1=value1¶m2=value2
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(list, charset));
        }
        return url;
    }
}

二、POST请求方式

1. 创建HttpClient实例。

2. 创建HttpPost请求方法实例,如果有带请求参数,需要另外封装参数,然后放到请求实例中。

封装方法,首先将请求参数以键和值的形式封装到NameValuePair实例中,将实例存放到List集合中,通过UrlEncodedFormEntity(list,charset)编码成合适的格式,使用setEntity()方法放到请求实例中。

3. 执行HttpPost实例,得到应答结果,从应答结果中可以获取应答行,应答消息体等。

4. 释放连接。

 public static void main(String[] args) throws IOException {
        String url = "https://login";
        Map<String, String> map = new HashMap();
        map.put("loginName","xxxxxxx");
        map.put("password","xxxxxx");
        String charset = "utf-8";
        doPost(url,map,charset);
    }
    public static String doPost(String url,Map<String,String> params,String charset) throws IOException {
        if(StringUtils.isBlank(url)){//检查url是否为null,""," "三种情况
            return null;
        }
        CloseableHttpClient client = HttpClients.createDefault();//创建HttpClient实例
        HttpPost httpPost = new HttpPost(url);//创建请求实例
        //将map中的请求参数封装到NameValuePair实例中,再将NameValuePair实例存放到List集合中
        List<NameValuePair> list = new ArrayList<>();
        if(params!=null && !params.isEmpty()){
            for(Map.Entry<String,String> entry:params.entrySet()){
                String key = entry.getKey();
                String value = entry.getValue();
                if(value!=null){
                    list.add(new BasicNameValuePair(key,value));
                }
            }
        }
        //集合中的请求参数被UrlEncodedFormEntity实例编码后变为:param1=value1¶m2=value2形式,放到post请求实例中
        if(list!=null && list.size()>0){
            httpPost.setEntity(new UrlEncodedFormEntity(list,charset));
        }
        CloseableHttpResponse response = client.execute(httpPost);//执行请求
        String line = response.getStatusLine().toString();//得到应答行
        HttpEntity entity = response.getEntity();//得到应答消息实例
        String result = EntityUtils.toString(entity,"utf-8");
        System.out.println(line);
        System.out.println(result);
        response.close();
        return line;
    }

三、https请求

https协议(Secure Hypertext Transfer Protocol) :

安全超文本传输协议, HTTPS以保密为目标研发, 简单讲HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、 身份认证的网络协议, 其安全基础是SSL协议, 因此加密的详细内容请看SSL。 全称Hypertext Transfer Protocol overSecure Socket Layer。句法类同http:体系。 用于安全的HTTP数据传输。 https:URL表明它使用了HTTP, 但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。

HTTPS和HTTP的区别:

1. https协议需要到ca申请证书, 一般免费证书很少, 需要交费。

2. http是超文本传输协议, 信息是明文传输, https 则是具有安全性的ssl加密传输协议。

3. http和https使用的是完全不同的连接方式, 用的端口也不一样, 前者是80,后者是443。

4. http的连接很简单, 是无状态的; HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、 身份认证的网络协议, 比http协议安全。

创建忽略证书校验的CloseableHttpClient类。

public class HttpsUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);
    static CloseableHttpClient httpClient;
    static CloseableHttpResponse httpResponse;

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
}

使用post方式发送https请求

public static String doPost(String url,Map<String,String> params) throws IOException {
        if(StringUtils.isBlank(url)){
            return null;
        }
        List<NameValuePair> list = new ArrayList<>();
        if(params!=null && !params.isEmpty()){
            Set<String> keyset = params.keySet();
            Iterator<String> it = keyset.iterator();
            while(it.hasNext()){
                String key = it.next();
                String value = params.get(key);
                if(value!=null){
                    NameValuePair np = new BasicNameValuePair(key,value);
                    list.add(np);
                }
            }
        }
        UrlEncodedFormEntity entity = null;
        if(list.size()>0){
            entity  = new UrlEncodedFormEntity(list,"utf-8");
        }
        //此处需要创建忽略校验证书的HttpClient类
        CloseableHttpClient client = HttpsUtils.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        CloseableHttpResponse  response = client.execute(httpPost);
        String line = response.getStatusLine().toString();
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        response.close();
        return line+System.getProperty("line.separator")+result;
    }

四、HttpClient需要的依赖包:

httpclient-4.0.1.jar
commons-codec-1.3.jar
commons-logging-1.1.1.jar
apache-mime4j-0.6.jar
httpcore-4.0.1.jar
httpmime-4.0.1.jar

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值