Java 实现 HTTP 请求的 4 种方式

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

使用 HttpURLConnection 类

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

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

示例代码

java 复制代码
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 服务器发送请求和处理响应的方法。

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

示例代码

java 复制代码
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.1 和 SPDY,可与 Retrofit 等网络请求框架搭配使用。

示例代码

java 复制代码
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 请求方法、请求头部定制、文件上传和下载等操作。

示例代码

java 复制代码
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"));
    }
}

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

相关推荐
源码宝15 分钟前
智慧工地云平台源码,基于微服务架构+Java+Spring Cloud +UniApp +MySql
java·大数据·源码·智慧工地·智能监测·智能施工
码不停蹄的玄黓44 分钟前
JUC核心解析系列(五)——执行框架(Executor Framework)深度解析
java·jvm·spring boot·spring cloud
白总Server1 小时前
GaussDB 分布式数据库调优(架构到全链路优化)
java·网络·c++·架构·go·scala·数据库架构
XiaoCCCcCCccCcccC1 小时前
传输层协议 TCP 介绍 -- TCP协议格式,确认应答机制,超时重传机制,连接管理机制,滑动窗口,流量控制,拥塞控制,延迟应答,捎带应答
网络·网络协议·tcp/ip
listhi5201 小时前
k8s使用私有harbor镜像源
java·docker·kubernetes
在未来等你1 小时前
Java并发编程实战 Day 21:分布式并发控制
java·多线程·并发编程
程序员小假1 小时前
你会不会使用 SpringBoot 整合 Flowable 快速实现工作流呢?
java·后端
来自外太空的鱼-张小张1 小时前
java将pdf文件转换为图片工具类
java·python·pdf
代码中の快捷键1 小时前
如何实现一个登录功能?
java·开发语言
保持学习ing2 小时前
微服务--消息队列mq
java·微服务·消息队列·rabbitmq·消息转换器