Java 实现HTTP请求的方式总结

前言

在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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,有多种方式可以实现HTTP请求。其中一种常见的方式是使用Java标准库中的HttpURLConnection类。这个类提供了发送HTTP请求和接收HTTP响应的功能。你可以使用HttpURLConnection类创建连接,并设置请求方法、请求头、请求体等,然后发送请求并获取响应。具体的代码可以参考以下示例: ``` import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置请求方法,例如GET、POST等 connection.setConnectTimeout(5000); // 设置连接超时时间 connection.setReadTimeout(5000); // 设置读取超时时间 int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // 处理响应数据 } else { // 处理错误情况 } connection.disconnect(); // 断开连接 } } ``` 另外,你还可以使用第三方库来简化HTTP请求的过程,比如OkHttp和Spring的RestTemplate。使用OkHttp时,你可以创建一个OkHttpClient实例,并使用Request类来构建请求,然后发送请求并获取响应。以下是一个使用OkHttp的示例代码: ``` 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类来发送HTTP请求。RestTemplate封装了HTTP请求的各种方法,让你可以更方便地发送请求和处理响应。以下是一个使用RestTemplate的示例代码: ``` import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://www.example.com", String.class); String result = response.getBody(); System.out.println(result); } } ``` 以上是三种常见的Java实现HTTP请求的方法,你可以根据具体的需求选择适合的方式来发送HTTP请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 实现HTTP请求的四种方式总结](https://blog.csdn.net/qq_34383510/article/details/130627924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值