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;
}
}