httpClient4.3.5 post请求指定 ContentType.APPLICATION_FORM_URLENCODED
原创    sh_man    发表于:2018-08-14 15:09:48
  阅读 :107   收藏   编辑

maven依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
</dependency>

HttpUtil.java

public class HttpUtil {
	
	private static int  totalConn = 1500;
	
	private static RequestConfig config;
	
	static {
		
		config = RequestConfig.custom()
				.setConnectionRequestTimeout(60000)
				.setConnectTimeout(60000)
				.setSocketTimeout(60000)
				.build();
	}
	
	
	/**
     * 发送Http Post 请求
     * @param url 请求URL,
     * @param data 请求参数,data
     * @param charset 编码格式
     * @return 返回HttpResponseUtil实例
     * @throws ParseException
     * @throws IOException
     */
    public static HttpResponseUtil doPost(String url,String data,String charset) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpResponseUtil response = HttpResponseUtil.init();
        if(url == null)return response;
        HttpPost post = new HttpPost(url);
        StringEntity entry = new StringEntity(data, ContentType.APPLICATION_FORM_URLENCODED);
        post.setEntity(entry);
        CloseableHttpResponse httpResponse  = httpClient.execute(post);
        RequestLine requestLine = post.getRequestLine();
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setUri(requestLine.getUri());
        response.setMethod(requestLine.getMethod());
        response.setProtocolVersion(requestLine.getProtocolVersion());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
            response.setHtml(EntityUtils.toString(entity));
            response.setContentEncoding(entity.getContentEncoding()+"");
            response.setContentLength(entity.getContentLength());
            response.setContentType(entity.getContentType().getValue());
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
        return response;
    }
    
    
}


评论
条评论