常见的Http连接方式介绍。
1、HttpURLConnection
HttpURLConnection继承自最原始的URLConnection,是jdk自带的标准类,无需下载其他jar包。 如果接口响应码被服务端修改则无法接收到返回报文,只能当响应码正确时才能接收到返回 HttpURLConnection方式调用。缺点:无连接池
//ms超时毫秒,url地址,json入参
public static String httpJson(int ms,String url,String json) throws Exception{
String err = "00", line = null;
StringBuilder sb = new StringBuilder();
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try{
conn = (HttpURLConnection) (new URL(url.replaceAll("/","/"))).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(ms);
conn.setReadTimeout(ms);
conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
conn.connect();//建立连接
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
out.write(new String(json.getBytes(), "utf-8"));
out.flush();//发送参数
int code = conn.getResponseCode();//此时才真正发送请求
if (conn.getResponseCode()==200){//响应码正确时才继续处理
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
while ((line=in.readLine())!=null)
sb.append(line);
}//接收返回值
…
}
2、Java.net.http.HttpClient
jdk11自带的HttpClient,代替HttpURLConnection
3、Apache HttpClient
需引入jar包,支持连接池。只用关注于如何发请求,接收响应,以及管理HTTP连接。
CloseableHttpClient:HttpClient4.3以上版本支持CloseableHttpClient。
public static String httpPostJson(String url,String json) throws Exception{
String data="";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();//1、创建连接
HttpPost httppost = new HttpPost(url);//2、创建Http请求对象
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity se = new StringEntity(json,Charset.forName("UTF-8"));
se.setContentType("text/json");
se.setContentEncoding("UTF-8");
httppost.setEntity(se);
response = httpClient.execute(httppost);//3、调用execute方法执行请求
…
}
HttpClient与CloseableHttpClient对比:httpclient是一个线程安全的类,没有必要由每个线程在每次使用时创建,全局保留一个即可。ClosableHttpClient默认会创建一个大小为5的连接池,CloseableHttpClient实现了Closeable接口,可以自动关闭资源,不需要在手动关闭资源了
4、okHttp
不需要手动关闭,支持http2 okHttp:
private OkHttpClient client = new OkHttpClient();//1、创建连接
@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
//请求参数
JSONObject json = new JSONObject();
json.put("name", "hetiantian");
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(json));
Request request = new Request.Builder()//2、创建Request对象
.url(url)
.post(requestBody) //post请求
.build();
final Call call = client.newCall(request);//3、将Request 对象封装为Call
Response response = call.execute();//4、通过Call 来调用execute方法执行
System.out.println(response.body().string());
}
下面介绍微服务中的使用
1、RestTemplate spring提供的用于访问Rest服务的,底层使用HttpURLConnection,无连接池
2、Openfeign:远程调用