JAVA工具【二】HttpClient常用封装

说明:没有使用工具类的方式是为了封装

public class HttpClientService {

	private static final String DEFAULT_CHARSET = "UTF-8";

	private CloseableHttpClient httpclient;
	private CookieStore cookieStore;
	private HttpClientContext localContext;
	private String charset;
	private static final String FILE_COLUMN = "fileColumn";

	public HttpClientService() {
		httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		cookieStore = new BasicCookieStore();
		localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);
		this.charset = DEFAULT_CHARSET;
	}

	public HttpClientService(String charset) {
		httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		cookieStore = new BasicCookieStore();
		localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);
		this.charset = charset;
	}

	public void closeHttpClient() {
		IOUtils.closeQuietly(httpclient);
	}

	public void login(String url, Map<String, String> params) throws  IOException {
		this.doPost(url, params);
	}

	public String doGet(String url) throws Exception  {
		return this.doGet(url, null, null);
	}


	public String doGet(String url, Map<String, String> params) throws Exception {
		return this.doGet(url, params, null);
	}

	public String doGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException, URISyntaxException {
		if (MapUtils.isNotEmpty(params)) {
			URIBuilder uriBuilder = new URIBuilder(url);
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				uriBuilder.addParameter(key, params.get(key));
			}
			url = uriBuilder.build().toString();
		}

		HttpGet httpget = new HttpGet(url);
		setHeaders(headers, httpget);
		CloseableHttpResponse response = httpclient.execute(httpget, localContext);
		return this.getResult(response);
	}


	public String doPost(String url, Map<String, String> params) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
		return this.doModify(httpPost, params);
	}
	
	/**
	 *根据不同的ContentType提交请求 
	 */
	public String postVariable(String url, String str,String contentType,String charset) throws Exception {
		HttpPost post = new HttpPost(url);
		StringEntity entity = new StringEntity(str,charset);
		entity.setContentType(contentType);
		entity.setContentEncoding(charset);
		post.setEntity(entity);
		CloseableHttpResponse response = httpclient.execute(post);
		return getResult(response);
	}

	public String doPut(String url, Map<String, String> params) throws IOException {
		HttpPut httpPut = new HttpPut(url);
		return this.doModify(httpPut, params);
	}

	public String doDelete(String url, Map<String, String> params) throws IOException {
		HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
		return this.doModify(httpDelete, params);
	}

	private String doModify(HttpEntityEnclosingRequestBase requestBase, Map<String, String> params) throws IOException {
		List<NameValuePair> parametersList = new ArrayList<>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			NameValuePair parameters = new BasicNameValuePair(key, params.get(key));
			parametersList.add(parameters);
		}

		requestBase.setEntity(new UrlEncodedFormEntity(parametersList, DEFAULT_CHARSET));

		CloseableHttpResponse response = httpclient.execute(requestBase, localContext);

		final List<Cookie> cookies = cookieStore.getCookies();
		for (Cookie cookie : cookies) {
			log.info(cookie.getName() + ":" + cookie.getValue());
		}

		return this.getResult(response);
	}

	public static String getResult(CloseableHttpResponse response) throws ParseException, IOException {
		try {
			int status = response.getStatusLine().getStatusCode();
			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				String result = entity != null ? EntityUtils.toString(entity, DEFAULT_CHARSET) : null;
				EntityUtils.consume(entity);
				return result;
			} else {
				throw new ClientProtocolException("Unexpected response status: " + status);
			}
		} finally {
			IOUtils.closeQuietly(response);
		}
	}

	public String doPostFile(String url, File file) throws IOException {
		HttpPost httpPost = new HttpPost(url);
		return this.doModifyFile(httpPost, file);
	}

	private String doModifyFile(HttpEntityEnclosingRequestBase requestBase, File file)
			throws ParseException, IOException {
		MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
		multipartEntityBuilder = multipartEntityBuilder.addBinaryBody(FILE_COLUMN, file);
		HttpEntity httpEntity = multipartEntityBuilder.build();
		requestBase.setEntity(httpEntity);
		CloseableHttpResponse response = httpclient.execute(requestBase, localContext);
		return this.getResult(response);
	}

	/**
	 * 设置头信息
	 * @param headers
	 * @param httpRequestBase
	 */
	private static void setHeaders(Map<String, String> headers, HttpRequestBase httpRequestBase) {
		if (MapUtils.isNotEmpty(headers)) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpRequestBase.setHeader(entry.getKey(), entry.getValue());
			}
		}
	}

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值