httpclient封装

pom文件:

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

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.7</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

代码:

package com.example.demo.server;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;

@Component
public class HttpRequest {
    private static final Logger log = LoggerFactory.getLogger(HttpRequest.class);
    /**
     * 使用HttpClient以JSON格式发送post请求
     * @param urlParam
     * @param jsonparams
     * @param socketTimeout
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public static String httpClientPost(String urlParam,String jsonparams,Integer socketTimeout) throws NoSuchAlgorithmException, KeyManagementException, UnsupportedEncodingException, IOException{
        StringBuffer resultBuffer = null;
        CloseableHttpClient httpclient=HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(urlParam);
        RequestConfig requestConfig = RequestConfig.custom()  
                .setConnectTimeout(3000).setConnectionRequestTimeout(1500)  
                .setSocketTimeout(socketTimeout).build();  
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json");
        // 构建请求参数
        BufferedReader br = null;
        try {
        if(null!=jsonparams&&jsonparams.length()>0){
                StringEntity entity = new StringEntity(jsonparams,"utf-8");
                httpPost.setEntity(entity);
        }
       
         CloseableHttpResponse response = httpclient.execute(httpPost);

        // 读取服务器响应数据
        resultBuffer = new StringBuffer();
        if(null!=response.getEntity()){
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }    
        }
        } catch (RuntimeException e) {
            log.error("网络链接出现异常,请检查...",e);
            throw new RuntimeException(e);
        } catch (ConnectException e) {
            log.error("客户端网络无法链接,请检查...",e);
            throw new ConnectException();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }        
        return resultBuffer.toString();
    }
    /**
     * 方式一:HttpClient解决以post方式,用json传输x-www-form-urlencoded数据
     */
    public  static  String doPostJson(String url,String key,String json){
        try {
            String postURL=url;
            PostMethod postMethod = null;
            postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            postMethod.addParameter(key,json);  //传参数
            HttpClient httpClient = new HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String result = postMethod.getResponseBodyAsString() ;
            return result;
        } catch (Exception e) {

            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 方式二:HttpClient解决以post方式,用json传输x-www-form-urlencoded数据
     */
    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig =
                RequestConfig.custom()
                        .setConnectTimeout(35000) // 设置连接主机服务超时时间
                        .setConnectionRequestTimeout(35000) // 设置连接请求超时时间
                        .setSocketTimeout(60000) // 设置读取数据连接超时时间
                        .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }



    /**
     * 使用HttpClient以JSON格式发送get请求
     * @param urlParam
     * @param params
     * @param socketTimeout
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws NoHttpResponseException
     */
    public static String httpClientGet(String urlParam, Map<String, Object> params,Integer socketTimeout) throws NoSuchAlgorithmException, KeyManagementException,NoHttpResponseException {
        StringBuffer resultBuffer = null;
        CloseableHttpClient httpclient=HttpClients.createDefault();
        BufferedReader br = null;
        // 构建请求参数
        StringBuffer sbParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            for (Entry<String, Object> entry : params.entrySet()) {
                sbParams.append(entry.getKey());
                sbParams.append("=");
                try {
                    sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                sbParams.append("&");
            }
        }
        if (sbParams != null && sbParams.length() > 0) {
            urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
        }
        HttpGet httpGet = new HttpGet(urlParam);
        RequestConfig requestConfig = RequestConfig.custom()  
                .setConnectTimeout(3000).setConnectionRequestTimeout(1500)  
                .setSocketTimeout(socketTimeout).build(); 
        httpGet.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            
            // 读取服务器响应数据
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
            String temp;
            resultBuffer = new StringBuffer();
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }
    

    /**
     * 上传文件
     * @param urlParam
     * @param loadpath
     * @param file
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws HttpHostConnectException
     * @author Seagull
     * @date 2019年3月15日
     */
    public static String httpClientUploadFile(String urlParam, String loadpath, File file) throws NoSuchAlgorithmException, KeyManagementException, HttpHostConnectException {
        StringBuffer resultBuffer = null;
        CloseableHttpClient httpclient=HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(urlParam);
        // 构建请求参数
        BufferedReader br = null;
        try {
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            //设置请求的编码格式  
            entityBuilder.setCharset(Charset.forName("utf-8"));
            entityBuilder.addBinaryBody("jarfile", file);
            entityBuilder.addTextBody("loadpath", loadpath);
            HttpEntity reqEntity =entityBuilder.build();
            httpPost.setEntity(reqEntity);
            
            CloseableHttpResponse response = httpclient.execute(httpPost);
             //从状态行中获取状态码  
             String responsecode = String.valueOf(response.getStatusLine().getStatusCode());
            // 读取服务器响应数据
            resultBuffer = new StringBuffer();

            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            if(resultBuffer.length()==0){
                resultBuffer.append("上传文件异常,响应码:"+responsecode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

    /**
     * httpclicent 发送form-data请求,没有上传文件
     * @param urlParam  请求url
     * @param requestParams 请求参数
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws HttpHostConnectException
     */
    public static String httpClientUploadPost(String urlParam, Map<String,Object> requestParams) throws NoSuchAlgorithmException, KeyManagementException, HttpHostConnectException
    {
        StringBuffer resultBuffer = null;
        CloseableHttpClient httpclient=HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(urlParam);
        // 构建请求参数
        BufferedReader br = null;
        try {
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            //设置请求的编码格式
            entityBuilder.setCharset(Charset.forName("utf-8"));
//        entityBuilder.addBinaryBody("jarfile", file);
            if (requestParams!=null&&requestParams.size()>0){
                for (Map.Entry<String, Object> entry: requestParams.entrySet()) {
                    entityBuilder.addTextBody(entry.getKey(), (String) entry.getValue());
                }
            }
            HttpEntity reqEntity =entityBuilder.build();
            httpPost.setEntity(reqEntity);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            //从状态行中获取状态码
            String responsecode = String.valueOf(response.getStatusLine().getStatusCode());
            // 读取服务器响应数据
            resultBuffer = new StringBuffer();

            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            if(resultBuffer.length()==0){
                resultBuffer.append("上传文件异常,响应码:"+responsecode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

    /**
     * 获取文件流
     * @param urlParam
     * @param params
     * @return
     * @throws IOException
     * @throws HttpHostConnectException
     * @author Seagull
     * @date 2019年3月15日
     */
    public static byte[] getFile(String urlParam, Map<String, Object> params) throws IOException, HttpHostConnectException{
        // 构建请求参数
        StringBuffer sbParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            for (Entry<String, Object> entry : params.entrySet()) {
                sbParams.append(entry.getKey());
                sbParams.append("=");
                try {
                    sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                sbParams.append("&");
            }
        }
        if (sbParams != null && sbParams.length() > 0) {
            urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
        }
        URL urlConet = new URL(urlParam);
        HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();    
        con.setRequestMethod("GET");    
        con.setConnectTimeout(4 * 1000);    
        InputStream inStream = con .getInputStream();    //通过输入流获取图片数据    
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
        byte[] buffer = new byte[2048];    
        int len = 0;    
        while( (len=inStream.read(buffer)) != -1 ){    
            outStream.write(buffer, 0, len);    
        }    
        inStream.close();
        byte[] data =  outStream.toByteArray(); 
        return data;
    }

}

 

 

测试代码:

public class TestHttp {
  public static void main(String[] args) {
    String url="https://xxxxxxxxx";
    String json ="xxxxx";
String body
= HttpRequest.doPostJson(url, "body", json); Map<String, Object> map = new HashMap<>(); map.put("body", json); String doPost = HttpRequest.doPost(url, map); System.out.println("这是第一种方式:"+body); System.out.println("这是第二种方式:"+doPost); } }

 

posted @ 2020-12-15 16:46  悦文  阅读(875)  评论(0编辑  收藏  举报