SpringBoot实战发送HTTP/HTTPS请求(HttpURLConnection、HttpClient、OkhttpRestTemplate)
在Spring Boot中,我们可以使用以下几种方式来发送HTTP/HTTPS请求:
- 使用Java的HttpURLConnection类
- 使用Apache的HttpClient库
- 使用OkHttp库
以下是每种方法的示例代码:
- 使用HttpURLConnection类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public String sendRequestUsingHttpURLConnection(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 接收响应代码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
return reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
- 使用Apache的HttpClient库:
首先,你需要在你的pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
然后,你可以使用以下代码:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public String sendRequestUsingHttpClient(String url) {
HttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
- 使用OkHttp库:
首先
评论已关闭