HttClient工具使用

Posted jwmdlm

tags:

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

1、导入依赖

技术图片
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>

        <!--gson工具,封装http用-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
View Code

2、封装get和post

get方法返回json格式字符串,使用Gson将json转化为map

package net.xdclass.xdvidio.utils;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.net.www.http.HttpClient;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Pandas
 * @Date 2020/4/9 22:41
 * @Version 1.0
 * @Description 封装HTTP get post
 */
public class HttpUtils {
    static Map<String,Object> map=new HashMap<>();
    private static final Gson gson=new Gson();
    /**
     * get
     * @param url
     * @return
     */
    public static Map<String,Object> doGet(String url){
        CloseableHttpClient httpClient=HttpClients.createDefault();

        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(5000)//连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//允许自动重定向
                .build();

        HttpGet httpGet=new HttpGet(url);
        httpGet.setConfig(requestConfig);
        try{
           HttpResponse httpResponse= httpClient.execute(httpGet);
           if(httpResponse.getStatusLine().getStatusCode()==200){
               String jsonResult= EntityUtils.toString(httpResponse.getEntity());
               map=gson.fromJson(jsonResult,map.getClass());
           }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){e.printStackTrace();}
        }
        return map;
    }

    /**
     * 封装post
     * @return
     */
    public static String doPost(String url,String data,Integer timeout){
        CloseableHttpClient httpClient=HttpClients.createDefault();

        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader("Content-Type","text/html;chartset=UTF-8");

        //设置超时时间
        RequestConfig requestConfig=RequestConfig.custom().setConnectTimeout(timeout)//连接超时
                .setConnectionRequestTimeout(timeout)//请求超时
                .setSocketTimeout(timeout)
                .setRedirectsEnabled(true)//允许自动重定向
                .build();
        httpPost.setConfig(requestConfig);

        if(data!=null&&data instanceof String){
            //使用字符串传参
            StringEntity stringEntry=new StringEntity(data,"UTF-8");
            httpPost.setEntity(stringEntry);
        }
        try{
            CloseableHttpResponse httpResponse=httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            if(httpResponse.getStatusLine().getStatusCode()==200){
                String result=EntityUtils.toString(httpEntity);
                return result;
            }

        }catch (Exception e){e.printStackTrace();}
        finally {
            try{
                httpClient.close();
            }catch(Exception e){e.printStackTrace();}

        }

        return null;
    }
}

3、总结套路

1、实例化httpClient

2、实例化http请求(httpGet/httpPost/eta)

3、给请求添加信息

  post请求的请求头(addHeader),请求体(setEntity)

  实例化请求配置requestConfig,并加载到请求中,eta

4、httpClient服务器执行http请求,并返回httpResponse

  从httpResponse中获取所需信息

5、关闭httpClient。

 

以上是关于HttClient工具使用的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

Word 文档的优秀代码片段工具或插件?

使用导航从工具栏菜单项单击在片段之间传递数据 - Kotlin

前端开发工具vscode如何快速生成代码片段

前端开发工具vscode如何快速生成代码片段

elasticsearch代码片段,及工具类SearchEsUtil.java