以下是利用Java实现调用HTTP请求的完整攻略。
简介
在Java中,我们可以使用HttpURLConnection或者Apache HttpClient来实现HTTP请求。两者区别在于HttpURLConnection是内置于Java SDK中的,而Apache HttpClient是第三方库。以下分别讲解这两种方式的使用方法。
使用HttpURLConnection实现HTTP请求
- 创建
URL
对象,指定请求的URL地址。
URL url = new URL("http://example.com/api");
- 使用
url.openConnection()
方法打开一个连接并得到HttpURLConnection
对象。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- 设置请求方法和请求头信息。
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
- 添加请求参数,并发送请求。
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.flush();
os.close();
- 接收响应。
int status = connection.getResponseCode();
InputStream inputStream;
if (status >= 400) {
inputStream = connection.getErrorStream();
} else {
inputStream = connection.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
完整代码示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String POST_URL = "http://example.com/api";
private static final String POST_PARAMS = "{\n" + "\"name\": \"John\",\r\n" + "\"age\": 31,\r\n" + "\"city\": \"New York\"\r\n" + "}";
public static void main(String[] args) throws Exception {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
}
使用Apache HttpClient实现HTTP请求
- 导入
httpclient
和httpcore
两个依赖包。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
- 创建
CloseableHttpClient
对象。
CloseableHttpClient httpclient = HttpClients.createDefault();
- 创建
HttpPost
对象,并设置请求头信息。
HttpPost httppost = new HttpPost("http://example.com/api");
httppost.setHeader("Content-type", "application/json; charset=UTF-8");
- 添加请求参数,并执行请求。
StringEntity params = new StringEntity(json.toString(),"UTF-8");
httppost.setEntity(params);
HttpResponse response = httpclient.execute(httppost);
- 接收响应。
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
完整代码示例:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class HttpClientExample {
public static void main(String[] args) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://example.com/api");
httppost.setHeader("Content-type", "application/json; charset=UTF-8");
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 31);
json.put("city", "New York");
StringEntity params = new StringEntity(json.toString(),"UTF-8");
httppost.setEntity(params);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
}
}
以上就是利用Java实现调用HTTP请求的完整攻略,两种方式均已详细讲解,并且分别提供了一个完整代码示例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用Java实现调用http请求 - Python技术站