java之发送HTTP的post请求代码实例

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

	/**
	 * 发送HTTL的POST请求
	 * @param url
	 * @param jsonString
	 * @param timeout
	 * @return
	 */
	public static String doPost(String url, String jsonString,int timeout) {

		try (CloseableHttpClient client = HttpClientBuilder.create().build();) {
			HttpPost httpost = new HttpPost(url);
			httpost.addHeader(HTTP.CONTENT_TYPE, "application/json");
			httpost.addHeader("ACCEPT-LANGUAGE", "zh-Hans");
			httpost.addHeader(HTTP.CONTENT_ENCODING, "identity");

			logger.info("do post url={}", url);
			logger.info("do post entity={},length={}", jsonString, jsonString.length());

			httpost.setEntity(new StringEntity(jsonString, "UTF-8"));

			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
					.setConnectTimeout(timeout).build();
			httpost.setConfig(requestConfig);

			HttpResponse resp = client.execute(httpost);
			HttpEntity he = resp.getEntity();
			String respContent = EntityUtils.toString(he, "UTF-8");
			logger.info("post response={}", respContent);
			return respContent;
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("doPost eror at:{}", e);
			return String.format("doPost eror at:%s", e);
		}

	}


你可能感兴趣的:(json,python,开发语言)