当前位置:首页 > Java

java如何发送http请求

2026-03-03 19:54:53Java

使用 HttpURLConnection

Java 原生提供了 HttpURLConnection 类用于发送 HTTP 请求。以下是一个简单的 GET 请求示例:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://example.com/api");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println("Response: " + response.toString());
    }
}

使用 Apache HttpClient

Apache HttpClient 是一个更强大的 HTTP 客户端库。以下是发送 POST 请求的示例:

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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();
        HttpPost httpPost = new HttpPost("https://example.com/api");

        String json = "{\"key\":\"value\"}";
        StringEntity entity = new StringEntity(json);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(httpPost);
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");

        System.out.println("Response: " + responseString);
        httpClient.close();
    }
}

使用 OkHttp

OkHttp 是一个现代高效的 HTTP 客户端。以下是发送异步 GET 请求的示例:

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

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://example.com/api")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("Response: " + response.body().string());
            }
        });
    }
}

使用 Spring RestTemplate

Spring 框架提供了 RestTemplate 用于简化 HTTP 请求:

import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("https://example.com/api", String.class);
        System.out.println("Response: " + result);
    }
}

使用 Java 11+ HttpClient

Java 11 引入了新的 HttpClient API:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class JavaHttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com/api"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Response: " + response.body());
    }
}

每种方法各有优缺点,HttpURLConnection 是 Java 原生支持,Apache HttpClient 功能强大但较重量级,OkHttp 性能优异,RestTemplate 适合 Spring 项目,Java 11+ HttpClient 是最新的标准 API。根据项目需求和 Java 版本选择合适的方法。

java如何发送http请求

标签: javahttp
分享给朋友:

相关文章

如何使用java

如何使用java

安装Java开发环境 下载并安装Java Development Kit(JDK),推荐从Oracle官网或OpenJDK获取最新版本。安装完成后配置环境变量,确保JAVA_HOME指向JDK安装路径…

java如何编译

java如何编译

编译Java程序的基本步骤 安装JDK(Java Development Kit)并配置环境变量。确保javac和java命令可在命令行中运行。JDK是编译和运行Java程序的必备工具。 创建Ja…

java如何自学

java如何自学

确定学习目标和路径 自学Java需要明确目标,例如开发Web应用、Android应用或后端服务。根据目标选择学习重点,如Java基础、Spring框架或Android开发。制定阶段性计划,从基础语法到…

如何安装java环境

如何安装java环境

下载JDK安装包 访问Oracle官方网站或OpenJDK项目页面,选择适合操作系统的JDK版本(如Windows、macOS或Linux)。确保下载与系统架构匹配的版本(32位或64位)。 运行…

java如何编写接口

java如何编写接口

编写Java接口的基本语法 在Java中,接口通过interface关键字定义,可以包含抽象方法、默认方法、静态方法和常量。 public interface MyInterface {…

java如何遍历map

java如何遍历map

遍历Map的几种方法 在Java中,遍历Map有多种方式,可以根据需求选择合适的方法。以下是常见的几种遍历方式: 使用entrySet遍历 通过entrySet()方法获取键值对的集合,可以同时访…