Java 实现HTTP请求的四种方式总结

前言

在日常工作和学习中,有很多地方都需要发送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(),方便开发者自由地控制请求和响应

示例代码:

import java.net.*;
import java.io.*;

public class HttpURLConnectionExample {

    private static HttpURLConnection con;

    public static void main(String[] args) throws Exception {

        URL url = new URL("https://www.example.com");
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        con.disconnect();

        System.out.println(content.toString());
    }
}

二、使用 HttpClient 库

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

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

示例代码:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("https://www.example.com");
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            System.out.println(result);
        } finally {
            response.close();
        }
    }
}

三、使用 Okhttp 库

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

示例代码:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkhttpExample {

    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        Request request = new Request.builder()
        	.url("https://www.example.com")
        	.build();
        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            System.out.println(result);
        }
    }
}

四、使用 Spring 的 RestTemplate

RestTemplate 是 Spring 库中用于访问 REST API 的类,它基于 HttpMessageConverter 接口,可以将 Java 对象转换为请求参数或响应内容。
RestTemplate 还支持各种 HTTP 请求方法、请求头部定制、文件上传和下载等操作。

示例代码:

public class HttpTemplate {

    public static String httpGet(String url) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
        return result;
    }

    public static String httpPost(String url, String name) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, name, String.class).getBody();
    }

    public static void main(String str[]) {
        System.out.println(HttpTemplate.httpGet("https://www.example.com"));
        System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
    }
}

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

总结

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

⭕关注博主,不迷路 ⭕

创作不易,关注💖、点赞👍、收藏🎉就是对作者最大的鼓励👏,欢迎在下方评论留言🧐

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Java中,有多种方式可以实现HTTP请求。其中一种常见的方式是使用Java标准库中的HttpURLConnection类。这个类提供了发送HTTP请求和接收HTTP响应的功能。你可以使用HttpURLConnection类创建连接,并设置请求方法、请求头、请求体等,然后发送请求并获取响应。具体的代码可以参考以下示例: ``` import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置请求方法,例如GET、POST等 connection.setConnectTimeout(5000); // 设置连接超时时间 connection.setReadTimeout(5000); // 设置读取超时时间 int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // 处理响应数据 } else { // 处理错误情况 } connection.disconnect(); // 断开连接 } } ``` 另外,你还可以使用第三方库来简化HTTP请求的过程,比如OkHttp和Spring的RestTemplate。使用OkHttp时,你可以创建一个OkHttpClient实例,并使用Request类来构建请求,然后发送请求并获取响应。以下是一个使用OkHttp的示例代码: ``` import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { private static final OkHttpClient client = new OkHttpClient(); public static void main(String[] args) throws IOException { Request request = new Request.Builder() .url("https://www.example.com") .build(); try (Response response = client.newCall(request).execute()) { String result = response.body().string(); System.out.println(result); } } } ``` 如果你使用Spring框架,你可以使用RestTemplate类来发送HTTP请求。RestTemplate封装了HTTP请求的各种方法,让你可以更方便地发送请求和处理响应。以下是一个使用RestTemplate的示例代码: ``` import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://www.example.com", String.class); String result = response.getBody(); System.out.println(result); } } ``` 以上是三种常见的Java实现HTTP请求的方法,你可以根据具体的需求选择适合的方式来发送HTTP请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 实现HTTP请求四种方式总结](https://blog.csdn.net/qq_34383510/article/details/130627924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.猫的树

你的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值