HttpCient 工具类

本文介绍了如何在Java中使用ApacheHttpClient库进行HTTPGET、POST请求,包括参数编码、JSON数据发送、表单数据模拟上传以及处理HTTPS请求。详细展示了如何构造请求、设置请求头和解析响应内容。
摘要由CSDN通过智能技术生成
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;

public class HttpClientUtils {

    /**
     * HttpCient Get 请求
     * @param url
     * @param params 请求参数应该是 name1=value1&name2=value2 的形式。
     * @param headers
     * @return
     * @throws Exception
     */
    public static String sendHttpClientGet(String url, String params, Map<String,String> headers) {
        HttpClient httpClient;
        HttpGet getMethod;
        HttpResponse response;
        String reponseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            url = url + "?" + params;
            getMethod = new HttpGet(url);
            if(null == headers){
                getMethod.addHeader("Content-type", "text/plain;charset=utf-8");
                getMethod.addHeader("accept", "*/*");
                getMethod.addHeader("connection", "Keep-Alive");
            }else{
                //遍历请求头
                for(Map.Entry<String,String> entry : headers.entrySet()){
                    getMethod.addHeader(entry.getKey(),entry.getValue());
                }
            }
            response = httpClient.execute(getMethod);
            HttpEntity httpEntity = response.getEntity();
            reponseContent = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reponseContent;
    }

    /**
     * HttpClient post 请求  参数为json格式
     * @param url
     * @param params   json 字符串
     * @param headers
     * @return
     */
    public static String sendHttpClientPost(String url,String params,Map<String,String> headers) {

        HttpClient httpClient;
        HttpPost postMethod;
        HttpResponse response;
        String reponseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);
            if(null == headers){
                //设置请求头
                postMethod.addHeader("Content-type", "text/plain;charset=utf-8");
                postMethod.addHeader("accept", "*/*");
                postMethod.addHeader("connection", "Keep-Alive");
            }else{
                //遍历请求头
                for(Map.Entry<String,String> entry : headers.entrySet()){
                    postMethod.addHeader(entry.getKey(),entry.getValue());
                }
            }


            postMethod.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
            response = httpClient.execute(postMethod);
            System.out.println("response =" +response);
            HttpEntity httpEntity = response.getEntity();
            reponseContent = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reponseContent;
    }


    /**
     * 模拟表单提交 post 请求
     * @param url
     * @param param
     * @param headers
     * @return
     */
    public static String sendHttpClientPost(String url, Map<String, String> param,Map<String,String> headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // url = url+"?merchantKey="+param.get("merchantKey")+"&merchantTransactionIds="+param.get("merchantTransactionIds");
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            for(Map.Entry<String,String> entry : headers.entrySet()){
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }


    /**
     * 通过  multipart/form-data 请求  上传文件形式
     * @param map
     * @param url
     * @param charset
     * @return
     */
    public static String postByFormData(Map<String,Object> map, String url,String charset,Map<String,String> headers) {
        HttpClient httpClient = HttpClients.createDefault();//从连接池中获取
        HttpPost post = new HttpPost(url);
        if(null != headers){
            for(Map.Entry<String,String> head : headers.entrySet()){
                post.setHeader(head.getKey(), head.getValue());//去掉Header
            }
        }
        BufferedReader br = null;
        try
        {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            if(map!=null) {
                Iterator iter = map.entrySet().iterator();
                while(iter.hasNext()){
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = String.valueOf(entry.getKey());
                    String value = String.valueOf(entry.getValue());
                    multipartEntityBuilder.addTextBody(key,value);
                }
            }
            HttpEntity httpEntity=multipartEntityBuilder.build();
            // 设置请求参数
            post.setEntity(httpEntity);
            // 发起交易
            HttpResponse resp = httpClient.execute(post);
            int ret = resp.getStatusLine().getStatusCode();
            // 响应分析
            HttpEntity entity = resp.getEntity();
            br = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuffer responseString = new StringBuffer();
            String result = br.readLine();
            while (result != null)
            {
                responseString.append(result);
                result = br.readLine();
            }
            return responseString.toString();
        } catch (Exception e)
        {
            e.getMessage();
            return "";
        } finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                } catch (IOException e)
                {
                    e.getMessage();
                }
            }
        }
    }

    /**
     * 为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
     * SSLClientUtils
     * @param url
     * @param jsonstr
     * @param charset
     * @return
     */
    @SuppressWarnings("resource")
    public static String sendHttpSSLClientPost(String url,String jsonstr,String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClientUtils();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) {
        String url = "http://localhost/admin.php/user/test/test";
        String param = "a=1&b=2&c=3";
        Map<String,String> headers = new HashMap<>();
        headers.put("Content-type","application/x-www-form-urlencoded");
        // headers.put("Content-type","multipart/form-data");
        //headers.put("Content-type","application/json");
        String s = sendHttpClientPost(url,param,headers);
        System.out.println(s);
    }
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值