本文为博主原创,未经允许不得转载:

  在项目中会用到各种类型的http请求,包含put,get,post,delete,formData等各种请求方式,在这里总结一下

用过比较好的请求工具,使用service方法封装。

  代码如下:

1.依赖的maven

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

2.封装请求返回的实体类

@Setter 
@Getter 
public class ApacheHttpClientResult { 
 
    /** 状态码 **/ 
    private int statusCode; 
 
    /** 响应内容 **/ 
    private String responseContent; 
}

3.封装各类型请求的方法

import java.util.Map; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
 
import com.vo.ApacheHttpClientResult; 
 
 
public interface ApacheHttpClientService { 
 
 
    public ApacheHttpClientResult postForJson(String uri, String param) throws CustomException; 
     
 
    public ApacheHttpClientResult postForJson(String uri, MultipartEntityBuilder param)throws CustomException; 
 
 
    public ApacheHttpClientResult getForObject(String uri)throws CustomException; 
 
 
    public ApacheHttpClientResult putForJson(String uri, String param)throws CustomException; 
 
 
    public ApacheHttpClientResult deleteForJson(String uri, String param)throws CustomException; 
 
 
    public ApacheHttpClientResult postForJson(String uri, String param, Map<String, String> headers)throws CustomException; 
 
 
    public ApacheHttpClientResult getForObject(String uri, Map<String, String> headers)throws CustomException; 
 
 
    public ApacheHttpClientResult putForJson(String uri, String param, Map<String, String> headers)throws CustomException; 
 
 
    public ApacheHttpClientResult deleteForJson(String uri, String param, Map<String, String> headers)throws CustomException; 
 
 
    public ApacheHttpClientResult getForObjectCloud(String uri, Map<String, String> headers) throws CustomException; 
 
 
    public ApacheHttpClientResult getForObjectCloud(String uri) throws CustomException; 
     
    public ApacheHttpClientResult postForJsonNoProxy(String uri, String param) throws CustomException; 
 
 
    public ApacheHttpClientResult postForJson(String uri, String param, Map<String, String> headers, Map<String, String> resultHeaders); 
 
 
    public ApacheHttpClientResult putForJson(String uri, String param, Map<String, String> headers,  Map<String, String> resultHeaders); 
 
}

4.实现类

import java.io.Closeable; 
import java.io.IOException; 
import java.net.Proxy; 
import java.util.Map; 
 
import org.apache.commons.lang3.StringUtils; 
import org.apache.http.Header; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpHost; 
import org.apache.http.client.config.RequestConfig; 
import org.apache.http.client.config.RequestConfig.Builder; 
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.client.methods.HttpPut; 
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.HttpClientBuilder; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.util.EntityUtils; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.http.MediaType; 
import org.springframework.stereotype.Service; 
 
import com.common.CustomException; 
import com.common.HttpDeleteWithBody; 
import com.intf.service.common.ApacheHttpClientService; 
import com.vo.ApacheHttpClientResult; 
 
@Service("apacheHttpClientService12") 
public class Test  implements ApacheHttpClientService{ 
     
    private final static Boolean enabled = false; 
 
    private final static String host = "127.0.0.1"; 
 
    private final static Integer port = 8080; 
 
    private final static int timeOut=20000; 
 
    private final static Boolean proxyEnabled= false; 
 
    private static final Logger LOGGER = LoggerFactory.getLogger(ApacheHttpClientServiceImpl.class); 
 
    /** 
     *  
     * 功能描述: <br> 
     * 创建默认Builder 
     * 
     * @return 
     * @see [相关类/方法](可选) 
     * @since [产品/模块版本](可选) 
     */ 
    private Builder createBuilder() { 
        // init Builder and init TIME_OUT 
        return RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut) 
                .setConnectionRequestTimeout(timeOut); 
    } 
 
    @Override 
    public ApacheHttpClientResult postForJson(String uri, String param) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
         
        CloseableHttpResponse response = null; 
        try { 
            // 定义Post请求 
            HttpPost httpPost = new HttpPost(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPost.setConfig(config); 
            // 设置请求头 
            httpPost.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            // 发送请求得到返回数据 
            httpPost.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPost); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult getForObject(String uri) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpGet 
            HttpGet httpGet = new HttpGet(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpGet.setConfig(config); 
            // 发送请求得到返回数据 
            response = httpClient.execute(httpGet); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity, "UTF-8"); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult putForJson(String uri, String param) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpPut 
            HttpPut httpPut = new HttpPut(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPut.setConfig(config); 
            // 设置请求头 
            httpPut.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            // 发送请求得到返回数据 
            httpPut.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPut); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult deleteForJson(String uri, String param) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpDelete 
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpDelete.setConfig(config); 
            // 设置请求头 
            httpDelete.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpDelete.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            // 发送请求得到返回数据 
            httpDelete.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpDelete); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult postForJson(String uri, String param, Map<String, String> headers) 
            throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // 定义Post请求 
            HttpPost httpPost = new HttpPost(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPost.setConfig(config); 
            // 设置请求头 
            httpPost.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpPost.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            httpPost.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPost); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult getForObject(String uri, Map<String, String> headers) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpGet 
            HttpGet httpGet = new HttpGet(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpGet.setConfig(config); 
            // 设置请求头 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpGet.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            response = httpClient.execute(httpGet); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
            LOGGER.info(uri + "&&&&&" + response.toString() + "&&&&&" + responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult putForJson(String uri, String param, Map<String, String> headers) 
            throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpPut 
            HttpPut httpPut = new HttpPut(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPut.setConfig(config); 
            // 设置请求头 
            httpPut.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpPut.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            httpPut.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPut); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
            LOGGER.info(uri + "&&&&&" + response.toString() + "&&&&&" + param); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult deleteForJson(String uri, String param, Map<String, String> headers) 
            throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpDelete 
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpDelete.setConfig(config); 
            // 设置请求头 
            httpDelete.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpDelete.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpDelete.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            httpDelete.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpDelete); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult getForObjectCloud(String uri, Map<String, String> headers) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpGet 
            HttpGet httpGet = new HttpGet(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (proxyEnabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpGet.setConfig(config); 
            // 设置请求头 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpGet.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            response = httpClient.execute(httpGet); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult getForObjectCloud(String uri) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpGet 
            HttpGet httpGet = new HttpGet(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (proxyEnabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpGet.setConfig(config); 
            // 发送请求得到返回数据 
            response = httpClient.execute(httpGet); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity, "UTF-8"); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult postForJsonNoProxy(String uri, String param) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // 创建默认的httpClient实例 
            httpClient = HttpClients.createDefault(); 
            // 定义Post请求 
            HttpPost httpPost = new HttpPost(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = builder.build(); 
            httpPost.setConfig(config); 
            // 设置请求头 
            httpPost.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            // 发送请求得到返回数据 
            httpPost.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPost); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult postForJson(String uri, MultipartEntityBuilder fileBuilder) throws CustomException { 
         // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // 定义Post请求 
            HttpPost httpPost = new HttpPost(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPost.setConfig(config); 
            // 设置请求头 
            //httpPost.setHeader("Content-Type", "multipart/form-data"); 
            // 发送请求得到返回数据 
            httpPost.setEntity(fileBuilder.build()); 
            // 得到响应 
            response = httpClient.execute(httpPost); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult postForJson(String uri, String param, Map<String, String> headers, Map<String, String> resultHeaders) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // 定义Post请求 
            HttpPost httpPost = new HttpPost(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPost.setConfig(config); 
            // 设置请求头 
            httpPost.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpPost.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            httpPost.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPost); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            Header header = response.getFirstHeader("Location"); 
            if (header != null && StringUtils.isNotBlank(header.getValue())) { 
                String location = header.getValue(); 
                String maCertificateId = location.substring(header.getValue().lastIndexOf('/') + 1, location.length()); 
                resultHeaders.put("Location", maCertificateId); 
            } 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
 
    @Override 
    public ApacheHttpClientResult putForJson(String uri, String param, Map<String, String> headers, 
        Map<String, String> resultHeaders) throws CustomException { 
        // 定义返回 
        ApacheHttpClientResult result = new ApacheHttpClientResult(); 
        // 定义httpClient和response 
         CloseableHttpClient httpClient = HttpClientBuilder.create().build();; 
        CloseableHttpResponse response = null; 
        try { 
            // HttpPut 
            HttpPut httpPut = new HttpPut(uri); 
            // 设置配置 
            Builder builder = createBuilder(); 
            RequestConfig config = null; 
            // 是否开启代理模式访问 
            if (enabled) { 
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString()); 
                config = builder.setProxy(proxy).build(); 
            } else { 
                config = builder.build(); 
            } 
            httpPut.setConfig(config); 
            // 设置请求头 
            httpPut.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE); 
            httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); 
            if (headers != null) { 
                for (Map.Entry<String, String> entry : headers.entrySet()) { 
                    httpPut.setHeader(entry.getKey(), entry.getValue()); 
                } 
            } 
            // 发送请求得到返回数据 
            httpPut.setEntity(new StringEntity(param, "UTF-8")); 
            // 得到响应 
            response = httpClient.execute(httpPut); 
            // 状态码 
            result.setStatusCode(response.getStatusLine().getStatusCode()); 
            // 响应内容 
            HttpEntity entity = response.getEntity(); 
            // 响应内容 
            String responseContent = EntityUtils.toString(entity); 
            result.setResponseContent(responseContent); 
            Header header = response.getFirstHeader("Location"); 
            if (header != null && StringUtils.isNotBlank(header.getValue())) { 
                String location = header.getValue(); 
                String maCertificateId = location.substring(header.getValue().lastIndexOf('/') + 1, location.length()); 
                resultHeaders.put("Location", maCertificateId); 
            } 
            LOGGER.info(uri + "&&&&&" + response.toString() + "&&&&&" + param); 
        } catch (Exception e) { 
            throw new CustomException(e); 
        } finally { 
            // 关闭流 
            closeStream(response); 
            closeStream(httpClient); 
        } 
        return result; 
    } 
     
    public static void closeStream(Closeable c) { 
        // 流不为空 
        if (c != null) { 
            try { 
                // 流关闭 
                c.close(); 
            } catch (IOException ex) { 
                LOGGER.error("closeStream failed", ex); 
            } 
        } 
    } 
}

5.依赖的类:

@NotThreadSafe 
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { 
 
    private static final String METHOD_NAME = "DELETE"; 
 
    /** 
     * 获取方法(必须重载) 
     *  
     * @return 
     */ 
    @Override 
    public String getMethod() { 
        return METHOD_NAME; 
    } 
 
    public HttpDeleteWithBody(final String uri) { 
        super(); 
        setURI(URI.create(uri)); 
    } 
 
    public HttpDeleteWithBody(final URI uri) { 
        super(); 
        setURI(uri); 
    } 
 
    public HttpDeleteWithBody() { 
        super(); 
    } 
}
public class CustomException extends Exception { 
 
    private static final long serialVersionUID = 8984728932846627819L; 
 
    public CustomException() { 
        super(); 
    } 
 
    public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 
        super(message, cause, enableSuppression, writableStackTrace); 
    } 
 
    /** 
 
    public CustomException(String message, Throwable cause) { 
        super(message, cause); 
    } 
 
 
    public CustomException(String message) { 
        super(message); 
    } 
 
    public CustomException(Throwable cause) { 
        super(cause); 
    } 
 
}

发布评论

分享到:

IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

为excel自动增加目录知识解答
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。