httpclient以json格式请求接口
原创    crazywind    发表于:2018-11-21 13:42:18
  阅读 :53   收藏   编辑
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


public class HttpUtils {
	
	private static int  totalConn = 1500;
	
	private static RequestConfig config;
	
	static {
		
		config = RequestConfig.custom()
				.setConnectionRequestTimeout(60000)
				.setConnectTimeout(60000)
				.setSocketTimeout(60000)
				.build();
	}
	
	
	/**
	 * httpclient已json格式请求接口
	 * @param url
	 * @param jsonStr
	 * @throws ParseException
	 * @throws IOException
	 */
    public static void doPost(String url,String jsonStr) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(jsonStr));
        CloseableHttpResponse httpResponse  = httpClient.execute(post);
        System.err.println(httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
        	System.err.println(EntityUtils.toString(entity));
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
    }
    
    
   
}


评论
条评论