HttpClient介绍和简单使用流程

Posted kitor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient介绍和简单使用流程相关的知识,希望对你有一定的参考价值。

HttpClient

SpringCloud中服务和服务之间的调用全部是使用HttpClient,还有前面使用SolrJ中就封装了HttpClient,在调用SolrTemplate的saveBean方法时就调用HttpClient技术。

当前大部分项目暴漏出来的接口是Http请求,数据格式是JSON格式,但在一些老项目使用的仍然是webService。

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

1、关于Http的请求类型(常见)

get、put、post、delete含义与区别

1、GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。

2、与GET不同的是,PUT请求是向服务器端发送数据的,从而改变信息,该请求就像数据库的update操作一样,用来修改数据的内容,但是不会增加数据的种类等,也就是说无论进行多少次PUT操作,其结果并没有不同。

3、POST请求同PUT请求类似,都是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。

4、DELETE请求顾名思义,就是用来删除某一个资源的,该请求就像数据库的delete操作。

就像前面所讲的一样,既然PUT和POST操作都是向服务器端发送数据的,那么两者有什么区别呢。。。POST主要作用在一个集合资源之上的(url),而PUT主要作用在一个具体资源之上的(url/xxx),通俗一下讲就是,如URL可以在客户端确定,那么可使用PUT,否则用POST。

数据请求格式

综上所述,我们可理解为以下:

1、POST    /url      创建  
2、DELETE /url/xxx 删除  
3、PUT     /url/xxx 更新
4、GET     /url/xxx 查看

2、HttpClient的请求类型

实现了所有的Http请求类型,相应的类为

HttpGet、HttpPost、HttpDelete、HttpPut

3、Http的使用流程

3.1 创建sms的war子模块

3.2 导入坐标

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
    </dependencies>

 

3.3 测试demo,原生HttpClient使用

3.3.1 新建HttpClientGetTest.java测试类,测试get请求

public static void main(String[] args) throws IOException 
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
        //3.发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4.判断状态码
        if(response.getStatusLine().getStatusCode()==200)
            HttpEntity entity = response.getEntity();
           //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        
        //5.关闭资源
        response.close();
        httpClient.close();
    

3.3.2 新建HttpClientPostTest.java测试类,测试post请求

public static void main(String[] args) throws IOException 
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpPost httpPost = new HttpPost("https://www.oschina.net/");
        //3.开源中国为了安全,防止恶意攻击,在post请求中都限制了浏览器才能访问
        httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        //4.判断状态码
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");

        httpPost.setEntity(formEntity);

        //5.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        if(response.getStatusLine().getStatusCode()==200)
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        
        //6.关闭资源
        response.close();
        httpClient.close();
    

 

3.3.3 测试获取运营商品牌数据代码实现

自定义工具类HttpClientUtil如果能直接访问,简单的访问实现。

//设置请求地址
HttpClientUtil util=new HttpClientUtil("http://localhost:9101/brand/findAll.do");
//设置请求方式
util.get();
//获取返回内容
String content=util.getContent();
//打印结果
System.out.println("content");

 

使用HttpClientUtil实现先登录在访问页面

要点:务必保证登录和查询请求是连续的请求。借助的自定义工具类HttpClientUtil

public class HttpClientTest 
    public static void main(String[] args) 
        //设置用户名和密码
        Map<String, String> map = new HashMap<String,String>();
        map.put("username", "admin");
        map.put("password", "123456");

        //需要先通过springSecurity认证
        String s1 = HttpClientUtil.doPost("http://localhost:9101/login", map);

        Map<String, String> brand = new HashMap<String,String>();
        brand.put("name", "123456");
        brand.put("firstChar", "T");

        String jsonMap = JSON.toJSONString(brand);
        System.out.println(jsonMap);
        String s2 = HttpClientUtil.doPostJson("http://localhost:9101/brand/add.do", jsonMap);

        //String s2 = HttpClientUtil.doGet("http://localhost:9101/brand/findAll.do");
        System.out.println(s2);
    

 

自定义工具类源码HttpClientUtil。注意导入的依赖

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http请求客户端
 * 
 * @author Administrator
 * 
 */
public class HttpClientUtil 

    public  static HttpClientContext context = null;

    static 
        System.out.println("====================begin");
        context = HttpClientContext.create();
    

    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() 
        return isHttps;
    

    public void setHttps(boolean isHttps) 
        this.isHttps = isHttps;
    

    public String getXmlParam() 
        return xmlParam;
    

    public void setXmlParam(String xmlParam) 
        this.xmlParam = xmlParam;
    

    public HttpClientUtil(String url, Map<String, String> param) 
        this.url = url;
        this.param = param;
    

    public HttpClientUtil(String url) 
        this.url = url;
    

    public void setParameter(Map<String, String> map) 
        param = map;
    

    public void addParameter(String key, String value) 
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    

    public void post() throws ClientProtocolException, IOException 
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    

    public void put() throws ClientProtocolException, IOException 
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    

    public void get() throws ClientProtocolException, IOException 
        if (param != null) 
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) 
                if (isFirst)
                    url.append("?");
                else
                    url.append("&");
                url.append(key).append("=").append(param.get(key));
            
            this.url = url.toString();
        
        HttpGet http = new HttpGet(url);
        execute(http);
    

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) 
        if (param != null) 
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet())
                nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        
        if (xmlParam != null) 
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        
    

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException 
        CloseableHttpClient httpClient = null;
        try 
            if (isHttps) 
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() 
                            // 信任所有
                            public boolean isTrusted(X509Certificate[] chain,
                                    String authType)
                                    throws CertificateException 
                                return true;
                            
                        ).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
             else 
                httpClient = HttpClients.createDefault();
            
            CloseableHttpResponse response = httpClient.execute(http,context);
            try 
                if (response != null) 
                    if (response.getStatusLine() != null)
                        statusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();
                    // 响应内容
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                
             finally 
                response.close();
            
         catch (Exception e) 
            e.printStackTrace();
         finally 
            httpClient.close();
        
    

    public int getStatusCode() 
        return statusCode;
    

    public String getContent() throws ParseException, IOException 
        return content;
    

 

以上是关于HttpClient介绍和简单使用流程的主要内容,如果未能解决你的问题,请参考以下文章

简单的OkHttp使用介绍

.Net Core 3.0后台使用httpclient请求网络网页和图片_使用Core3.0做一个简单的代理服务器

Android HTTP请求方式

把HttpClient换成IHttpClientFactory之后,放心多了

HttpClient的简单运用

Angular 6 和 Spring boot - 无法使用简单的 HttpClient 调用获取数据