HttpUtils案例

wen java案例 3

本文目录导读:

HttpUtils案例

  1. 引入依赖(Maven)
  2. HttpUtils 工具类核心代码
  3. 具体使用案例(Demo)
  4. 使用 Spring Boot(RestTemplate)的简化版(备选)

下面给你一个HttpUtils的完整案例,包含常见的GETPOST上传文件下载文件以及带Header/Token的请求示例。

这个案例基于 Apache HttpClientJackson(处理JSON),这是目前最主流的写法,如果你用的是其他框架(如OkHttp、Spring RestTemplate),也可以根据注释做对应调整。


引入依赖(Maven)

<!-- Apache HttpClient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>
<!-- 处理JSON:Jackson -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>
<!-- 文件上传需要 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.14</version>
</dependency>

HttpUtils 工具类核心代码

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final int TIMEOUT = 10000; // 10秒超时
    private static final RequestConfig CONFIG = RequestConfig.custom()
            .setConnectTimeout(TIMEOUT)      // 连接超时
            .setSocketTimeout(TIMEOUT)       // 响应超时
            .setConnectionRequestTimeout(TIMEOUT)
            .build();
    // 全局单例(线程安全)
    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.custom()
            .setDefaultRequestConfig(CONFIG)
            .build();
    // ======================== GET 请求 ========================
    /**
     * GET请求,返回String
     */
    public static String doGet(String url, Map<String, String> headers) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        if (headers != null) {
            headers.forEach(httpGet::setHeader);
        }
        return executeAndReturnString(httpGet);
    }
    /**
     * GET请求,最简版(无Header)
     */
    public static String doGet(String url) throws IOException {
        return doGet(url, null);
    }
    // ======================== POST 请求 ========================
    /**
     * POST JSON,返回String
     * @param url 地址
     * @param jsonBody JSON字符串
     * @param headers 请求头(可传Token等)
     */
    public static String doPostJson(String url, String jsonBody, Map<String, String> headers) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        // 默认设置JSON
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (headers != null) {
            headers.forEach(httpPost::setHeader);
        }
        StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return executeAndReturnString(httpPost);
    }
    /**
     * POST 表单(application/x-www-form-urlencoded)
     */
    public static String doPostForm(String url, Map<String, String> formData) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        if (formData != null) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                if (sb.length() > 0) sb.append("&");
                sb.append(entry.getKey()).append("=").append(entry.getValue());
            }
            StringEntity entity = new StringEntity(sb.toString(), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
        }
        return executeAndReturnString(httpPost);
    }
    // ======================== 文件上传 ========================
    /**
     * 上传文件(multipart/form-data)
     * @param url 上传地址
     * @param file 本地文件
     * @param formData 其他表单字段(可选)
     */
    public static String doUploadFile(String url, File file, Map<String, String> formData) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8);
        // 添加文件字段,字段名为 file(可根据后端要求调整)
        FileBody fileBody = new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        builder.addPart("file", fileBody);
        // 添加普通表单字段
        if (formData != null) {
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN);
            }
        }
        httpPost.setEntity(builder.build());
        return executeAndReturnString(httpPost);
    }
    // ======================== 下载文件 ========================
    /**
     * 下载文件到本地
     * @param url 文件URL
     * @param savePath 保存路径(含文件名)
     */
    public static void doDownload(String url, String savePath) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                byte[] bytes = EntityUtils.toByteArray(entity);
                saveFile(bytes, savePath);
                System.out.println("文件下载成功:" + savePath);
            } else {
                throw new IOException("下载失败,状态码:" + response.getStatusLine().getStatusCode());
            }
        }
    }
    // ======================== 公共私有方法 ========================
    private static String executeAndReturnString(HttpUriRequest request) throws IOException {
        try (CloseableHttpResponse response = HTTP_CLIENT.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            if (statusCode >= 200 && statusCode < 300) {
                return result;
            } else {
                throw new IOException("HTTP错误码: " + statusCode + ",响应内容: " + result);
            }
        }
    }
    private static void saveFile(byte[] data, String filePath) throws IOException {
        File dir = new File(filePath).getParentFile();
        if (dir != null && !dir.exists()) {
            dir.mkdirs(); // 创建父目录
        }
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(data);
        }
    }
}

具体使用案例(Demo)

GET请求 + 带Token

public class TestGet {
    public static void main(String[] args) throws IOException {
        String url = "https://api.example.com/user/info";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer xxxx-token");
        headers.put("Accept", "application/json");
        String response = HttpUtils.doGet(url, headers);
        System.out.println("GET响应: " + response);
    }
}

POST 提交 JSON

public class TestPostJson {
    public static void main(String[] args) throws IOException {
        String url = "https://api.example.com/user/create";
        String jsonBody = "{\"name\":\"张三\", \"age\":25}";
        Map<String, String> headers = new HashMap<>();
        headers.put("token", "abc123");
        String response = HttpUtils.doPostJson(url, jsonBody, headers);
        System.out.println("POST响应: " + response);
    }
}

上传文件

public class TestUpload {
    public static void main(String[] args) throws IOException {
        String url = "https://api.example.com/upload/avatar";
        File file = new File("D:/photo.jpg");
        Map<String, String> extraForm = new HashMap<>();
        extraForm.put("userId", "1001");
        extraForm.put("source", "admin");
        String response = HttpUtils.doUploadFile(url, file, extraForm);
        System.out.println("上传响应: " + response);
    }
}

下载文件

public class TestDownload {
    public static void main(String[] args) throws IOException {
        String fileUrl = "https://example.com/templates/report.xlsx";
        String savePath = "D:/downloads/report.xlsx";
        HttpUtils.doDownload(fileUrl, savePath);
    }
}

使用 Spring Boot(RestTemplate)的简化版(备选)

如果你的项目是 Spring 生态,直接用 Spring 的 RestTemplate 更简洁:

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class SpringHttpUtils {
    private static final RestTemplate restTemplate = new RestTemplate();
    public static String doPostJson(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return response.getBody();
    }
    public static String doGet(String url, String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return response.getBody();
    }
}

功能点 方法名
GET请求 doGet(url, headers)
POST JSON doPostJson(url, json, headers)
POST 表单 doPostForm(url, formData)
上传文件 doUploadFile(url, file, formData)
下载文件 doDownload(url, savePath)

这个 HttpUtils 已经覆盖了日常开发 90% 以上的 HTTP 请求场景,可以直接复制到项目中使用,如果后端接口有特殊要求(如自定义域名、证书忽略),可以在 HttpClients.custom() 里额外配置。

上一篇JsonUtils案例

下一篇FileUtils案例

抱歉,评论功能暂时关闭!