122HttpClient学习笔记

             HttpClient学习笔记

1 HttpClient简介

​ HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效、最新的、功能丰富的支持Http协议的客户端工具包,

并且它支持Http协议最新的版本和建议。

​ Http协议可以能是现在Internet上使用最多的、最重要的协议了,越来越多的Java应用程序需要直接通过Http协议来访问网络资源。

虽然在JDK的Java net包中已经提供了访问http协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。

官网: https://hc.apache.org/ 使用版本:4.5.13

image-20220227233415535

使用场景:

​ 。爬虫

​ 。多系统之间接口调用(第三方接口请求)

2 JDK原生api发送http请求

JDK原生api请求: HttpURLConnection

121HttpURLConnection学习笔记 文档

3 环境搭建

maven依赖:

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.6</version>
</dependency>

4 HttpClient相关api

4.1 HttpClients.createDefault()

​ 创建可关闭的httpClient客户端

//可关闭的httpClient客户端,相当于你打开的浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();

4.2 new HttpGet(url)

构造httpGet请求对象

String password = URLEncoder.encode("123+456", "UTF-8");
String data = "username=tanguganlin&password="+password;
String url = "http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet?"+data;
//构造httpGet请求对象
HttpGet httpGet = new HttpGet(url);

4.3 httpGet.addHeader(name,value)

添加请求头信息

//加请求头  解决httpClient被认为不是真人行为
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 
                                                    (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
//防盗链   value的值:url要是发生防盗链的网站url
httpGet.addHeader("Referer","http://127.0.0.1:8080/jsp_servlet_project");

4.4 httpClient.execute(httpGet)

执行http get请求

CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

4.5 httpResponse.getEntity()

获取响应结果

//HttpEntity不仅可以作为响应结果的实体,也可以作为请求参数的实体,有很多的实现
HttpEntity entity = httpResponse.getEntity();

4.6 httpResponse.getStatusLine()

获取本次请求的状态

//代表本次请求的成功、失败的状态
StatusLine statusLine = httpResponse.getStatusLine();
//获取状态码:200就是成功
int statusCode = statusLine.getStatusCode();

4.7 httpResponse.getAllHeaders()

获取响应头信息

//获取响应头
Header[] allHeaders = httpResponse.getAllHeaders();
for(Header  header: allHeaders){
    System.out.println("响应头"+header.getName()+"的值:"+header.getValue());
}

4.8 entity.getContentType()

获取contentType信息

Header contentType = entity.getContentType();

4.9 EntityUtils.toString(entity)

将响应结果转为字符串

//对httpEntity操作的工具类
String str = EntityUtils.toString(entity);

4.10 EntityUtils.toByteArray(entity)

将响应结果转为字节数组,比如图片,视频

byte[] bytes = EntityUtils.toByteArray(entity);
fileOutputStream = new FileOutputStream("H:\\122HttpClient\\20220227233416.png");
fileOutputStream.write(bytes);

5 发送get请求

5.1 获取文本信息

package com.tangguanlin.httpclient;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLEncoder;
/**
 * 说明:HttpClient get提交
 *      1.无参请求
 *      2.加请求头
 *      3.有参请求
 * 作者:汤观林
 * 日期:2022年02月27日 23时
 */
public class HttpClientGetTest {
    public static void main(String[] args) throws IOException {

        //可关闭的httpClient客户端,相当于你打开的浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //特殊符号:做URLEncode  如果是浏览器,浏览器会自动帮我们做了   + 空格
        String password = URLEncoder.encode("123+456", "UTF-8");
        String data = "username=tanguganlin&password="+password;
        String url = "http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet?"+data;
        //构造httpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        //加请求头  解决httpClient被认为不是真人行为
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
        //防盗链   value的值:url要是发生防盗链的网站url
        httpGet.addHeader("Referer","http://127.0.0.1:8080/jsp_servlet_project");

        CloseableHttpResponse httpResponse = null;
        try {
             httpResponse = httpClient.execute(httpGet);
             //代表本次请求的成功、失败的状态
            StatusLine statusLine = httpResponse.getStatusLine();
            //获取状态码:200就是成功
            int statusCode = statusLine.getStatusCode();
            if(HttpStatus.SC_OK==statusCode){  //200就是请求成功

                //获取响应头
                Header[] allHeaders = httpResponse.getAllHeaders();
                for(Header  header: allHeaders){
                    System.out.println("响应头"+header.getName()+"的值:"+header.getValue());
                }

                //获取响应结果
                //HttpEntity不仅可以作为响应结果的实体,也可以作为请求参数的实体,有很多的实现
                HttpEntity entity = httpResponse.getEntity();

                Header contentType = entity.getContentType();
                System.out.println("contentType:"+contentType);

                //对httpEntity操作的工具类
                String str = EntityUtils.toString(entity);
                System.out.println(str);

            }else{
                System.out.println("请求失败,响应码是"+statusCode);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if(httpClient!=null){
                httpClient.close();
            }
            if(httpResponse!=null){
                httpResponse.close();
            }
        }
    }
}

运行结果:

响应头Server的值:Apache-Coyote/1.1
响应头Content-Type的值:text/html;charset=utf-8
响应头Content-Length的值:77
响应头Date的值:Tue, 01 Mar 2022 17:33:56 GMT
contentType:Content-Type: text/html;charset=utf-8
用户名:tanguganlin 密码:123+456
用户验证成功,谢谢访问

5.2 获取图片信息

package com.tangguanlin.httpclient;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
/**
 * 说明:获取图片
 * 作者:汤观林
 * 日期:2022年02月27日 23时
 */
public class HttpClientGetTest2 {
    public static void main(String[] args) throws IOException {

        //可关闭的httpClient客户端,相当于你打开的浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String url = "https://gitee.com/tangguanlin2006/image/raw/master/20220227233416.png";
        //构造httpGet请求对象
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = null;
        FileOutputStream fileOutputStream = null;
        try {
             httpResponse = httpClient.execute(httpGet);

            //获取响应结果
            //HttpEntity不仅可以作为响应结果的实体,也可以作为请求参数的实体,有很多的实现
            HttpEntity entity = httpResponse.getEntity();

            byte[] bytes = EntityUtils.toByteArray(entity);
            fileOutputStream = new FileOutputStream("H:\\122HttpClient\\20220227233416.png");
            fileOutputStream.write(bytes);
            
            //确保流关闭
            EntityUtils.consume(entity);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(httpClient!=null){
                httpClient.close();
            }
            if(httpResponse!=null){
                httpResponse.close();
            }
        }
    }
}

运行结果:

image-20220302013522300

6 发送post请求

6.1 发送表单类型的post请求

package com.tangguanlin.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 说明:application/x-www-form-urlencoded form表单
 * 作者:汤观林
 * 日期:2022年03月02日 13时
 */
public class HttpClientPostTest1 {
    public static void main(String[] args) throws IOException {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try{
            //创建httpClient
            httpClient = HttpClients.createDefault();

            String url = "http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet";
            HttpPost httpPost = new HttpPost(url);

            //设置请求格式 form表单格式
            httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //给httpPost对象设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            NameValuePair nameValuePair1 = new BasicNameValuePair("username","tangguanlin");
            list.add(nameValuePair1);
            NameValuePair nameValuePair2 = new BasicNameValuePair("password", "123");
            list.add(nameValuePair2);
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list);
            httpPost.setEntity(urlEncodedFormEntity);

            httpResponse = httpClient.execute(httpPost);

            HttpEntity entity = httpResponse.getEntity();
            String str = EntityUtils.toString(entity);
            System.out.println(str);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if(httpClient!=null){
                httpClient.close();
            }
            if(httpResponse!=null){
                httpResponse.close();
            }
        }
    }
}

6.2 发送json类型的post请求

package com.tangguanlin.httpclient;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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 java.io.IOException;
/**
 * 说明:application/json json格式数据
 * 作者:汤观林
 * 日期:2022年03月02日 15时
 */
public class HttpClientPostTest2 {
    public static void main(String[] args) throws IOException {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try{
            httpClient = HttpClients.createDefault();

            String url = "http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet";
            HttpPost httpPost = new HttpPost(url);
           //设置数据格式为json格式
            httpPost.setHeader("Content-Type","application/json;charset=utf-8");

            //设置json数据
            //这里的字符串是一个json字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username","tangguanlin");
            jsonObject.put("password","123");
            StringEntity jsonEntity = new StringEntity(jsonObject.toString());
            httpPost.setEntity(jsonEntity);

            httpResponse = httpClient.execute(httpPost);

            HttpEntity entity = httpResponse.getEntity();
            String str = EntityUtils.toString(entity);
            System.out.println(str);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if(httpClient!=null){
                httpClient.close();
            }
            if(httpResponse!=null){
                httpResponse.close();
            }
        }
    }
}

服务端Servlet解析json格式数据:

    ServletInputStream inputStream = request.getInputStream();
    StringBuffer sb = new StringBuffer();
    byte buffer[] = new byte[1024];
    int length = 0;

    while ((length=inputStream.read(buffer))!=-1){
        sb.append(new String(buffer,0,length));
    }
    String json =  sb.toString();

    JSONObject jsonObject =  JSONObject.parseObject(json);
    username = jsonObject.getString("username");
    password = jsonObject.getString("password");

6.3 发送文件上传的post请求

package com.tangguanlin.httpclient;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
 * 说明:文件上传 multipart/form-data
 * 作者:汤观林
 * 日期:2022年03月02日 16时
 */
public class HttpClientPostTest3 {
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();

            String url = "http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet";
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type","multipart/form-data;charset=utf-8");
            //构建上传文件使用的entity
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setCharset(Consts.UTF_8); //设置编码
            multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA); //文本类型
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //设置浏览器模式
            //组装数据
            FileBody fileBody = new FileBody(new File("H:\\122HttpClient\\333333.png"));
            StringBody usernameBody = new StringBody("小明", ContentType.TEXT_PLAIN);
            StringBody passwordBody = new StringBody("123", ContentType.TEXT_PLAIN);

            HttpEntity httpEntity = multipartEntityBuilder.addPart("filename", fileBody)
                                  //二进制文件
                      .addBinaryBody("filename", new FileInputStream("H:\\122HttpClient\\20220227233416.png")) 
                                                          .addPart("username",usernameBody)
                                                          .addPart("password",passwordBody)
                                                          .build();
            httpPost.setEntity(httpEntity);

            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpPost.getEntity();
            String str = EntityUtils.toString(entity);
            System.out.println(str);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if(httpClient!=null){
                httpClient.close();
            }
            if(httpResponse!=null){
                httpResponse.close();
            }
        }
    }
}

7 请求https连接

。安全的 https://www.baidu.com/

​ 和http一样请求即可

。不安全的

https://localhost:8888/httpsTest2

​ 1.通过认证需要的密钥配置httpClient

​ 2.配置httpClient绕过https安全认证 (平安证券资金管理系scms)

private ConnectionSocketFactory trustHttpsCertificates() throws Exception{
     SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
     SSLContext sslContext = sslContextBuilder.build();
    
     SSLConnectionSocketFactory(sslContext,new String[]                                                         
                    {"SSLv2Hello","SSLv3","TLSv1","TLSv1.1","TLSv1.2"},null,NoopHostnameVerifier.INSTANCE);
    return null;
}

(略)

8 使用HttpClient连接池

在游戏项目开发中,经常会向其它的服务发送一些Http请求,获取一些数据或验证。比如充值,SDK验证等。

如果每次都重新创建一个新的HttpClient对象的话,当并发上来时,容易出现异常或连接失败,超时。

这里可以使用HttpClient的连接池配置,减少HttpClient创建的数量,减少资源开销。

(略)

package com.tangguanlin.httpclient;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
/**
 * 说明:HttpClient连接池
 * 作者:汤观林
 * 日期:2022年03月03日 00时
 */
public class HttpClientUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    // 池化管理
    private static PoolingHttpClientConnectionManager poolConnManager = null;

    private static CloseableHttpClient httpClient;// 它是线程安全的,所有的线程都可以使用它一起发送http请求
    static {
        try {
            System.out.println("初始化HttpClientTest~~~开始");
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
            // 初始化连接管理器
            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            poolConnManager.setMaxTotal(640);// 同时最多连接数
            // 设置最大路由
            poolConnManager.setDefaultMaxPerRoute(320);
            // 此处解释下MaxtTotal和DefaultMaxPerRoute的区别:
            // 1、MaxtTotal是整个池子的大小;
            // 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;比如:
            // MaxtTotal=400 DefaultMaxPerRoute=200
            // 而我只连接到http://www.abc.com时,到这个主机的并发最多只有200;而不是400;
            // 而我连接到http://www.bac.com 和
            // http://www.ccd.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400);
                                               //所以起作用的设置是DefaultMaxPerRoute
            // 初始化httpClient
            httpClient = getConnection();

            System.out.println("初始化HttpClientTest~~~结束");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    public static CloseableHttpClient getConnection() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000)
                                                     .setConnectionRequestTimeout(5000)
                                                     .setSocketTimeout(5000)
                                                     .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                                                    //设置连接池管理
                                                    .setConnectionManager(poolConnManager)
                                                    .setDefaultRequestConfig(config)
                                                    //设置重试次数
                                              .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false))
                                              .build();
        return httpClient;
    }

    public static String httpGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                logger.error("请求{}返回错误码:{},{}", url, code,result);
                return null;
            }
        } catch (IOException e) {
            logger.error("http请求异常,{}",url,e);
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    public static String post(String uri, Object params, Header... heads) {
        HttpPost httpPost = new HttpPost(uri);
        CloseableHttpResponse response = null;
        try {
            StringEntity paramEntity = new StringEntity(JSON.toJSONString(params));
            paramEntity.setContentEncoding("UTF-8");
            paramEntity.setContentType("application/json");
            httpPost.setEntity(paramEntity);
            if (heads != null) {
                httpPost.setHeaders(heads);
            }
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                logger.error("请求{}返回错误码:{},请求参数:{},{}", uri, code, params,result);
                return null;
            }
        } catch (IOException e) {
            logger.error("收集服务配置http请求异常", e);
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

9 HttpClient工具类

HttpClientUtils2.java

package com.tangguanlin.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 说明:httpClient工具类
 * 作者:汤观林
 * 日期:2022年03月04日 21时
 */
public class HttpClientUtils2 {

    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("username","tangguanlin2006");
        map.put("password","123");
        String resultStr =  HttpClientUtils2.doPost("http://127.0.0.1:8080/jsp_servlet_project/MyHttpServlet",map);
        System.out.println(resultStr);
    }

    //get请求  有参
    public static String doGet(String url, Map<String,String> param)  {

        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String resultStr = "";
        String data = "";
        CloseableHttpResponse httpResponse = null;

        try{
           //组装参数
           if(param!=null){
               for(String key:param.keySet()){
                   data = key +"="+param.get(key)+"&";
               }
               data = data.substring(0,data.length()-1);
               //组装url
               url = url +"?"+ data;
           }

           //创建httpGet
           HttpGet httpGet = new HttpGet(url);
           //执行请求
           httpResponse = httpClient.execute(httpGet);

            if(httpResponse.getStatusLine().getStatusCode()==200){
                HttpEntity entity = httpResponse.getEntity();
                resultStr = EntityUtils.toString(entity);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(httpResponse!=null){
                try {
                    httpResponse.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return resultStr;
    }

    //get请求 无参
    public static String doGet(String url)  {
        return doGet(url,null);
    }

    //doPost  有参
    public static String doPost(String url,Map<String,String> param){

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String resultStr = "";

        try{
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if(param!=null){
                for(String key:param.keySet()){
                    BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, param.get(key));
                    list.add(basicNameValuePair);
                }
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list);
            httpPost.setEntity(urlEncodedFormEntity);

            httpResponse = httpClient.execute(httpPost);

            if(httpResponse.getStatusLine().getStatusCode()==200){
                HttpEntity entity = httpResponse.getEntity();
                resultStr = EntityUtils.toString(entity);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(httpResponse!=null){
                try {
                    httpResponse.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
         return resultStr;
    }

    //doPost  无参
    public static String doPost(String url){
      return   doPost(url,null);
    }

    public static  String doPostJson(String url,String json){

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String resultStr = "";

        try{
            //创建httpClient对象
            httpClient = HttpClients.createDefault();
            //创建httpPost
            HttpPost httpPost = new HttpPost(url);
            //创建请求内容
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            //执行http请求
            httpResponse = httpClient.execute(httpPost);

            if(httpResponse.getStatusLine().getStatusCode()==200){
                HttpEntity entity = httpResponse.getEntity();
                resultStr = EntityUtils.toString(entity);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(httpResponse!=null){
                try {
                    httpResponse.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
       return  resultStr;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值