NET2Java之十:HTTP请求
在微服务化大行其道的今天,http请求也是极为常见的功能之一,.NET中有HttpWebRequest和HttpClient,那java中该如何发送Http请求呢?
原生请求
Java原生提供了HttpURLConnection来发送Http请求,示例如下:
public class HttpUtil {
/**
* 原生Get请求。
*
* @param getUrl
* @return
* @throws Exception
*/
public static String sendGet(String getUrl) throws Exception {
URL httpUrl = new URL(getUrl);
HttpURLConnection httpConn = (HttpURLConnection) httpUrl.openConnection();
httpConn.setRequestMethod(HttpMethod.GET.name());
httpConn.setDoOutput(false); //标明是否从请求体发送数据到服务器
httpConn.setDoInput(true); //标明是否期望接收返回值数据
httpConn.setConnectTimeout(10); //10ms超时
httpConn.setReadTimeout(100); //100ms超时
//打开链接
httpConn.connect();
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
System.out.println("请求出错!");
return "";
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream input = httpConn.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
String httpReturn = output.toString("utf-8");
output.close();
input.close();
httpConn.disconnect();
return httpReturn;
}
/**
* 原生Post请求。
*
* @param postUrl
* @param postParams
* @return
* @throws Exception
*/
public static String sendPost(String postUrl, String postParams, String contentType) throws Exception {
URL httpUrl = new URL(postUrl);
HttpURLConnection httpConn = (HttpURLConnection) httpUrl.openConnection();
httpConn.setRequestMethod(HttpMethod.POST.name());
httpConn.setRequestProperty("Content-Type", contentType); //请求头,比如application/json; utf-8
httpConn.setRequestProperty("Accept", "application/json"); //返回值
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
dos.writeBytes(postParams);
dos.flush();
dos.close();
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
System.out.println("请求出错!");
return "";
}
InputStream ins = httpConn.getInputStream();
byte[] readBuffer = new byte[1024];
int len = 0;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((len = ins.read(readBuffer)) > 0) {
output.write(readBuffer, 0, len);
}
String httpReturn = output.toString("utf-8");
output.close();
ins.close();
httpConn.disconnect();
return httpReturn;
}
}
HttpClient
虽然原生的HttpURLConnection已经能够满足大多数业务场景,但随着时间的推移和技术的发展,其不可不免的出现了一些局限性,比如使用繁琐、性能和安全性有待提升等,所以一些三方包进行了优化和封装,比如Apache的HttpClient和OkHttp。
Maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
代码示例
public class HttpUtil {
private static final CloseableHttpClient httpClient = HttpClients.createDefault();
/**
* Apache HttpClient Get请求。
*
* @param getUrl
* @return
* @throws Exception
*/
public static String sendGet(String getUrl) throws Exception {
HttpGet hg = new HttpGet(getUrl);
hg.addHeader("token", "vLx8IAq9nybErhP7");
CloseableHttpResponse response = httpClient.execute(hg);
String httpReturn = EntityUtils.toString(response.getEntity());
response.close();
return httpReturn;
}
/**
* Apache HttpClient Post请求。
*
* @param postUrl
* @param postParams
* @return
* @throws Exception
*/
public static String sendPost(String postUrl, String postParams, String contentType) throws Exception {
HttpPost hp = new HttpPost(postUrl);
hp.setEntity(new StringEntity(postParams));
hp.setHeader("Content-Type", contentType);
hp.setConfig(RequestConfig.custom().setConnectTimeout(10).setSocketTimeout(3000).build()); //设置超时
CloseableHttpResponse response = httpClient.execute(hp);
String httpReturn = EntityUtils.toString(response.getEntity());
response.close();
return httpReturn;
}
}
OkHttp
另外一个广受欢迎的Http三方包则是OkHttp。
maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.1</version>
</dependency>
代码示例
public class HttpUtil {
private static final OkHttpClient httpClient = new OkHttpClient();
/**
* OkHttp Get请求。
*
* @param getUrl
* @return
* @throws Exception
*/
public static String sendGet(String getUrl) throws Exception {
Request request = new Request.Builder()
.url(getUrl)
.build();
Response response = httpClient.newCall(request).execute();
String httpReturn = "";
if (response.isSuccessful())
httpReturn = response.body().string();
response.close();
return httpReturn;
}
/**
* OkHttp Post请求。
*
* @param postUrl
* @param postParams
* @return
* @throws Exception
*/
public static String sendPost(String postUrl, String postParams, String contentType) throws Exception {
RequestBody postBody = RequestBody.create(MediaType.parse(contentType), postParams);
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
Response response = httpClient.newCall(request).execute();
String httpReturn = "";
if (response.isSuccessful())
httpReturn = response.body().string();
response.close();
return httpReturn;
}
}

浙公网安备 33010602011771号