HttpUtils

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
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.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	public static String postJson(String url, String jsonString) throws Exception {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "application/json;charset=UTF-8");
		return postJson(url, jsonString, headers);
	}

	public static String postJson(String url, String jsonString, Map<String, String> headers) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 超时都设计成5秒,超过了都认为异常了
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000)
				.setSocketTimeout(5000).build();
		try {
			HttpPost httpPost = new HttpPost(url);
			if (headers != null) {
				for (Map.Entry<String, String> header : headers.entrySet()) {
					httpPost.addHeader(header.getKey(), header.getValue());
				}
			}
			if (jsonString != null) {
				// 解决中文乱码问题
				StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
				stringEntity.setContentEncoding("UTF-8");
				httpPost.setEntity(stringEntity);
			}
			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {//
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}
			};
			httpPost.setConfig(requestConfig);
			return httpclient.execute(httpPost, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				httpclient.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
posted @ 2024-05-30 18:02  亲爱的阿道君  阅读(15)  评论(0编辑  收藏  举报