java httpClient调用http接口Util类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java httpClient调用http接口Util类相关的知识,希望对你有一定的参考价值。

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
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 HttpClientUtil {

	public static String post(String url, String json) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);
		// HttpPost post = new
		// HttpPost("http://localhost:8080/GYDCENTER/server/examplesso/putjson.do");
		String response = null;
		try {
			StringEntity s = new StringEntity(
					json, "UTF-8");

			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");// 发送json数据需要设置contentType
			post.setEntity(s);
			HttpResponse res = httpclient.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(res.getEntity());// 返回json格式:
				// response = new String(Base64.decodeBase64(result), "UTF-8");
				response = result;
			}

		} catch (Exception e) {
			// e.printStackTrace();
		}
		return response;

	}

	public static String get(String url) {
		String response = null;
		try {
			CloseableHttpClient httpclient = HttpClientBuilder.create().build();
			HttpGet get = new HttpGet(url);// httpclient也会自动编码中文
			get.setHeader("Content-Type", "application/json;charset=UTF-8");
			HttpResponse res = httpclient.execute(get);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(res.getEntity());// 返回json格式:
				// response = new String(Base64.decodeBase64(result), "UTF-8");
				response = result;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
}

以上是关于java httpClient调用http接口Util类的主要内容,如果未能解决你的问题,请参考以下文章

Java发送http get/post请求,调用接口/方法

java 通过httpclient调用https 的webapi

net怎么调用API接口

HttpClient连接池耗尽引发雪崩问题

httpClient 远程调用接口,java8新特性Optional

Java的HttpClient如何去支持无证书访问https