Java 实现 HTTP 请求的四种方式,你都学会了么?

偏执的太偏执、 2023-10-14 17:10 73阅读 0赞

前言

在日常工作和学习中,有很多地方都需要发送HTTP请求,本文以Java为例,总结发送HTTP请求的多种方式

HTTP请求实现过程

GET

  • 创建远程连接
  • 设置连接方式(get、post、put…)
  • 设置连接超时时间
  • 设置响应读取时间
  • 发起请求
  • 获取请求数据
  • 关闭连接

POST

  • 创建远程连接
  • 设置连接方式(get、post、put。。。)
  • 设置连接超时时间
  • 设置响应读取时间
  • 当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
  • 当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput
  • 设置传入参数的格式:(setRequestProperty
  • 设置鉴权信息:Authorization:(setRequestProperty)
  • 设置参数
  • 发起请求
  • 获取请求数据
  • 关闭连接

一、使用 HttpURLConnection 类

HttpURLConnection 是 Java 标准库中用来发送 HTTP 请求和接收 HTTP 响应的类。

它预先定义了一些方法,如 setRequestMethod()setRequestProperty()getResponseCode(),方便开发者自由地控制请求和响应。

示例代码:

  1. import java.net.*;
  2. import java.io.*;
  3. public class HttpURLConnectionExample {
  4. private static HttpURLConnection con;
  5. public static void main(String[] args) throws Exception {
  6. URL url = new URL("https://www.example.com");
  7. con = (HttpURLConnection) url.openConnection();
  8. con.setRequestMethod("GET");
  9. BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  10. String inputLine;
  11. StringBuffer content = new StringBuffer();
  12. while ((inputLine = in.readLine()) != null) {
  13. content.append(inputLine);
  14. }
  15. in.close();
  16. con.disconnect();
  17. System.out.println(content.toString());
  18. }
  19. }

二、使用 HttpClient 库

HttpClient 是一个 HTTP 客户端库,提供了向 HTTP 服务器发送请求和处理响应的方法。

它支持多种请求协议,如 GET、POST 等,并允许开发者自由地设置请求头、请求参数、连接池等。HttpClient 还提供了基于线程池的异步请求处理方式。

示例代码:

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpGet;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. public class HttpClientExample {
  8. public static void main(String[] args) throws Exception {
  9. CloseableHttpClient httpclient = HttpClients.createDefault();
  10. HttpGet httpget = new HttpGet("https://www.example.com");
  11. CloseableHttpResponse response = httpclient.execute(httpget);
  12. try {
  13. HttpEntity entity = response.getEntity();
  14. String result = EntityUtils.toString(entity);
  15. EntityUtils.consume(entity);
  16. System.out.println(result);
  17. } finally {
  18. response.close();
  19. }
  20. }
  21. }

三、使用 Okhttp 库

Okhttp 是由 Square 公司开发的一款轻量级网络请求库,支持普通的 HTTP/1.1 和 SPDY,可与 Retrofit 等网络请求框架搭配使用。

示例代码:

  1. import okhttp3.OkHttpClient;
  2. import okhttp3.Request;
  3. import okhttp3.Response;
  4. import java.io.IOException;
  5. public class OkhttpExample {
  6. private static final OkHttpClient client = new OkHttpClient();
  7. public static void main(String[] args) throws IOException {
  8. Request request = new Request.builder()
  9. .url("https://www.example.com")
  10. .build();
  11. try (Response response = client.newCall(request).execute()) {
  12. String result = response.body().string();
  13. System.out.println(result);
  14. }
  15. }
  16. }

四、使用 Spring 的 RestTemplate

RestTemplate 是 Spring 库中用于访问 REST API 的类,它基于 HttpMessageConverter 接口,可以将 Java 对象转换为请求参数或响应内容。

RestTemplate 还支持各种 HTTP 请求方法、请求头部定制、文件上传和下载等操作。

示例代码:

  1. public class HttpTemplate {
  2. public static String httpGet(String url) {
  3. RestTemplate restTemplate = new RestTemplate();
  4. String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
  5. return result;
  6. }
  7. public static String httpPost(String url, String name) {
  8. RestTemplate restTemplate = new RestTemplate();
  9. return restTemplate.postForEntity(url, name, String.class).getBody();
  10. }
  11. public static void main(String str[]) {
  12. System.out.println(HttpTemplate.httpGet("https://www.example.com"));
  13. System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
  14. }
  15. }

注:上述示例代码,我们并没有考虑网络请求可能失败的情况。在实际应用中,需要对异常进行捕获和处理。

总结

以上就是今天要讲的内容,本文仅仅简单介绍了 Java 中常见的几种发送 HTTP 请求的方式,可以根据实际需要选择合适的方式。

发表评论

表情:
评论列表 (有 0 条评论,73人围观)

还没有评论,来说两句吧...

相关阅读