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>

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。

相关推荐