前言
在Java应用程序中,发送HTTP请求是一项常见的任务,用于与远程服务器进行通信。在本文中,我将介绍几种常用的Java发送HTTP请求的方式,并为每种方式提供GET和POST请求的示例。
一、URLConnection
Java的java.net包提供了URLConnection类,可用于简单的HTTP请求。
1、Get请求示例
public static String sendGetRequest(String url, Map<String, String> params) throws Exception {
// 构建完整的URL
StringBuilder fullUrl = new StringBuilder(url);
if (params != null && !params.isEmpty()) {
fullUrl.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
// 移除末尾的"&"
fullUrl.deleteCharAt(fullUrl.length() - 1);
}
URL obj = new URL(fullUrl.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
2、Post请求示例
public int sendPostRequest(String url, String requestBody) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(requestBody.getBytes());
os.flush();
os.close();
return con.getResponseCode();
}
二、Apache HttpClient
Apache HttpClient是一个成熟且功能强大的HTTP客户端库。
1、引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2、Get请求示例
public static String sendGetRequest(String url, Map<String, String> params) throws Exception {
HttpClient httpClient = HttpClients.createDefault();
// 构建完整的URL
StringBuilder fullUrl = new StringBuilder(url);
if (params != null && !params.isEmpty()) {
fullUrl.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
// 移除末尾的"&"
fullUrl.deleteCharAt(fullUrl.length() - 1);
}
HttpGet httpGet = new HttpGet(fullUrl.toString());
HttpResponse response = httpClient.execute(httpGet);
try (BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
String inputLine;
StringBuilder result = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
return result.toString();
}
}
3、Post请求示例
public String sendPostRequest(String url, String requestBody) throws Exception {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity());
}
二、RestTemplate
Spring的RestTemplate是一个方便的HTTP客户端库,简化了HTTP请求的发送。
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、Get请求示例
public static String sendGetRequest(String url, Map<String, String> params) {
// 构建完整的URL
StringBuilder fullUrl = new StringBuilder(url);
if (params != null && !params.isEmpty()) {
fullUrl.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
// 移除末尾的"&"
fullUrl.deleteCharAt(fullUrl.length() - 1);
}
return restTemplate.getForObject(fullUrl.toString(), String.class);
}
3、Post请求示例
public JSONObject sendPostRequest(JSONObject jsonobj){
//创建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//构建请求参数
HttpEntity<JSONObject> requestEntity = new HttpEntity<>(jsonobj, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(basehxUrl, HttpMethod.POST, requestEntity, String.class);
return JSONObject.parse(responseEntity.getBody());
}