码迷,mamicode.com
首页 > 其他好文 > 详细

HttClient工具使用

时间:2020-04-10 00:30:52      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:服务   chart   获取   finally   cat   stc   请求头   charts   data   

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工具使用

标签:服务   chart   获取   finally   cat   stc   请求头   charts   data   

原文地址:https://www.cnblogs.com/jwmdlm/p/12670577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!