java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java发起HTTP请求

Java实现发起HTTP请求的四种方法实现与适用场景

作者:超级小忍

Java中发起HTTP请求有多种方式,包括原生库、第三方库及现代API,以下是常见的几种实现方法,本文介绍了它们的具体实现代码以及性能适用场景,感兴趣的可以了解下

使用HttpURLConnection(原生API)

HttpURLConnection是Java标准库提供的HTTP客户端,适合简单请求。

public class HttpUrlConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.example.com/data");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        
        int responseCode = conn.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    }
}

使用Apache HttpClient

Apache HttpClient是功能更丰富的第三方库,适合复杂场景。

public class ApacheHttpClientExample {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet("https://api.example.com/data");
        
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        }
    }
}

使用OkHttp

OkHttp是Square开发的现代HTTP客户端,性能优异且API简洁。

public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("https://api.example.com/data")
            .build();
        
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

使用Java 11+的HttpClient

Java 11引入的新HTTP客户端,支持异步和HTTP/2。

public class Java11HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.example.com/data"))
            .build();
        
        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

处理POST请求(以OkHttp为例)

POST请求需要构建请求体,以下是JSON提交示例。

public class OkHttpPostExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String jsonBody = "{\"name\":\"John\", \"age\":30}";
        
        Request request = new Request.Builder()
            .url("https://api.example.com/post")
            .post(RequestBody.create(jsonBody, JSON))
            .build();
        
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

总结对比

方法特点适用场景
HttpURLConnection原生支持,无需依赖简单GET/POST请求
Apache HttpClient功能全面,支持连接池企业级复杂HTTP交互
OkHttp高性能,简洁API移动端/高性能需求
Java 11 HttpClient现代API,支持异步和HTTP/2

Java 11+项目

可根据项目实际需求选择合适的方法。在现代项目推荐使用OkHttp或Java 11+ HttpClient。

到此这篇关于Java实现发起HTTP请求的四种方法实现与适用场景的文章就介绍到这了,更多相关Java发起HTTP请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文