使用httpclient进行 Http get请求带参数cookie

使用httpclient进行 Http get请求带参数cookie

常用的工具类,所有的包配置如下

    
    
        com.alibaba
        fastjson
        1.2.59
    
        
    
        org.apache.httpcomponents
        httpclient
        4.5.6
    
        
    
        org.slf4j
        slf4j-api
        1.7.25
    

一个类,一张代码完成

jdk没有特别的要求

//这句话用jdk1.7+

List params = new ArrayList<>();

否则写成

List params = new ArrayList();

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
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.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class HttpClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);
    public static final String HOST = "localhost";
    public static final int PORT = 8080;
    public static final String PATH = "/getInfo";

    public static String getInfo(){
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
        // 参数
        URI uri = null;
        try {
            // 将参数放入键值对类NameValuePair中,再放入集合中
            List params = new ArrayList<>();
            params.add(new BasicNameValuePair("param1", "param1"));
            params.add(new BasicNameValuePair("param2", "param2"));
            // 设置uri信息,并将参数集合放入uri;
            // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("http").setHost(HOST)
                    .setPort(PORT).setPath(PATH)
                    .setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            //设置cookie ---方式一 可能会出现不生效的情况
            BasicClientCookie cookie = new BasicClientCookie("token", "1234");
            cookie.setVersion(0);
            cookie.setPath("/");
            //设置Cookie的域
            cookie.setDomain("test.ggg.com.cn");
            cookieStore.addCookie(cookie);

            //设置cookie ---方式二 简单暴力
            httpGet.setHeader("Cookie","token=123;base=test.ggg.com.cn");

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("响应状态为:" + statusCode);
            if (statusCode!=200){
                LOGGER.error("http请求出错,http返回码:"+statusCode);
                throw new RuntimeException("服务器响应出现问题,无法执行业务");
            }
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                //EntityUtils 不可以反复读取,读取第二次为空
                String respStr = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + respStr);
                //转换成自己的业务代码,一般都是json传输,处理
                Object objc = JSON.parseObject(respStr,Object.class);
                return objc.toString();
            }else{
                throw new RuntimeException("服务器响应出现问题,----");
            }
        } catch (ClientProtocolException e) {
            LOGGER.error("ClientProtocolException,----",e);
            throw new RuntimeException("服务出现错误,请联系管理员");
        } catch (ParseException e) {
            LOGGER.error("ParseException,----",e);
            throw new RuntimeException("服务出现错误,请联系管理员");
        } catch (IOException e) {
            LOGGER.error("IOException,----",e);
            throw new RuntimeException("服务出现错误,请联系管理员");
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOGGER.error("IOException,释放连接失败",e);
            }
        }
    }

    public static void main(String[] args){
        String info = HttpClient.getInfo();
        System.out.println(info);
    }
}

 

你可能感兴趣的:(Java知识点综合)