Java 实现HTTP请求的方式总结

本文详细介绍了在Java程序中使用URLConnection、ApacheHttpClient和SpringRestTemplate发送GET和POSTHTTP请求的方法,包括代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在Java应用程序中,发送HTTP请求是一项常见的任务,用于与远程服务器进行通信。在本文中,我将介绍几种常用的Java发送HTTP请求的方式,并为每种方式提供GET和POST请求的示例。

一、URLConnection

Java的java.net包提供了URLConnection类,可用于简单的HTTP请求。

1、Get请求示例

    public static String sendGetRequest(String url, Map<String, String> params) throws Exception {
        // 构建完整的URL
        StringBuilder fullUrl = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            fullUrl.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            // 移除末尾的"&"
            fullUrl.deleteCharAt(fullUrl.length() - 1);
        }

        URL obj = new URL(fullUrl.toString());
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

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

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

        return response.toString();
    }

2、Post请求示例

 public int sendPostRequest(String url, String requestBody) throws Exception {
     URL obj = new URL(url);
     HttpURLConnection con = (HttpURLConnection) obj.openConnection();
     con.setRequestMethod("POST");
     con.setRequestProperty("Content-Type", "application/json");

     con.setDoOutput(true);
     OutputStream os = con.getOutputStream();
     os.write(requestBody.getBytes());
     os.flush();
     os.close();

     return con.getResponseCode();
 }

二、Apache HttpClient

Apache HttpClient是一个成熟且功能强大的HTTP客户端库。

1、引入依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

2、Get请求示例

public static String sendGetRequest(String url, Map<String, String> params) throws Exception {
       HttpClient httpClient = HttpClients.createDefault();

       // 构建完整的URL
       StringBuilder fullUrl = new StringBuilder(url);
       if (params != null && !params.isEmpty()) {
           fullUrl.append("?");
           for (Map.Entry<String, String> entry : params.entrySet()) {
               fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
           }
           // 移除末尾的"&"
           fullUrl.deleteCharAt(fullUrl.length() - 1);
       }

       HttpGet httpGet = new HttpGet(fullUrl.toString());

       HttpResponse response = httpClient.execute(httpGet);

       try (BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
           String inputLine;
           StringBuilder result = new StringBuilder();
           while ((inputLine = in.readLine()) != null) {
               result.append(inputLine);
           }
           return result.toString();
       }
   }

3、Post请求示例

    public String sendPostRequest(String url, String requestBody) throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        StringEntity requestEntity = new StringEntity(requestBody);
        httpPost.setEntity(requestEntity);
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity());
    }

二、RestTemplate

Spring的RestTemplate是一个方便的HTTP客户端库,简化了HTTP请求的发送。

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、Get请求示例

    public static String sendGetRequest(String url, Map<String, String> params) {
        // 构建完整的URL
        StringBuilder fullUrl = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            fullUrl.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                fullUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            // 移除末尾的"&"
            fullUrl.deleteCharAt(fullUrl.length() - 1);
        }

        return restTemplate.getForObject(fullUrl.toString(), String.class);
    }
    

3、Post请求示例

    public JSONObject sendPostRequest(JSONObject jsonobj){
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //构建请求参数
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(jsonobj, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(basehxUrl, HttpMethod.POST, requestEntity, String.class);
        return JSONObject.parse(responseEntity.getBody());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值