Java发起post和get请求

2023-12-15 23:30:45

本文分享两种方式,一种是使用HttpURLConnection ,另一种是使用 Apache HttpClient

使用 HttpURLConnection 发送 GET 请求:

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

public class GetRequestExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.example.com/data"); // 替换为你想要发送 GET 请求的 URL

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

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

                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("GET request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 HttpURLConnection 发送 POST 请求:

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

public class PostRequestExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.example.com/post_endpoint"); // 替换为你想要发送 POST 请求的 URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求类型为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 构建请求参数
            String params = "param1=value1&param2=value2"; // 替换为你的参数

            // 发送 POST 请求
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(params);
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

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

                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("POST request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上示例使用了 Java 中的 HttpURLConnection 类来发送 GET 和 POST 请求。需要替换 URL 和参数为你实际想要发送请求的地址和数据。

使用 Apache HttpClient 发送 GET 请求:

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;

public class ApacheHttpClientGetExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://api.example.com/data"); // 替换为你想要发送 GET 请求的 URL

            HttpResponse response = httpClient.execute(request);

            if (response.getStatusLine().getStatusCode() == 200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response: " + responseBody);
            } else {
                System.out.println("GET request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 Apache HttpClient 发送 POST 请求:

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;
import org.apache.http.HttpResponse;

public class ApacheHttpClientPostExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost("https://api.example.com/post_endpoint"); // 替换为你想要发送 POST 请求的 URL

            // 构建请求参数
            StringEntity params = new StringEntity("param1=value1&param2=value2"); // 替换为你的参数
            request.setEntity(params);
            request.addHeader("content-type", "application/x-www-form-urlencoded");

            HttpResponse response = httpClient.execute(request);

            if (response.getStatusLine().getStatusCode() == 200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response: " + responseBody);
            } else {
                System.out.println("POST request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

文章来源:https://blog.csdn.net/qq_39327650/article/details/135026482
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。