ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java http 请求

2023-12-27 17:20:52  阅读:81  来源: 互联网

标签:


在Java中,您可以使用java.net.HttpURLConnectionorg.apache.http.client.HttpClient等类来进行HTTP请求。以下是使用HttpURLConnection类发送GET和POST请求的示例代码:

发送GET请求:

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

public class HttpGetRequestExample {
    public static void main(String[] args) {
        try {
            String url = "https://api.example.com/get-data";
            
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("GET request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java

发送POST请求:

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

public class HttpPostRequestExample {
    public static void main(String[] args) {
        try {
            String url = "https://api.example.com/submit-data";
            String postData = "name=John&age=30"; // POST请求的数据

            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(postData.getBytes());
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("POST request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java

在上述示例中,我们使用HttpURLConnection类来发送HTTP请求。对于GET请求,我们设置请求方法为"GET",并使用getInputStream()方法来获取响应数据。对于POST请求,我们除了设置请求方法为"POST"外,还设置了是否输出请求数据,并将POST数据写入输出流。然后,我们使用getInputStream()方法来获取响应数据。

 

要在Java中发送带有JSON参数的POST请求,您可以使用java.net.HttpURLConnection类并设置请求的内容类型为"application/json"。以下是一个示例代码:

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

public class HttpPostJsonExample {
    public static void main(String[] args) {
        try {
            String url = "https://api.example.com/submit-data";
            String jsonInputString = "{\"name\": \"John\",\"age\": 30}"; // JSON参数

            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(jsonInputString.getBytes());
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("POST request failed. Response Code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java

在上述示例中,我们设置了请求方法为"POST",并在HttpURLConnection的请求头中设置了"Content-Type"为"application/json",表示我们将发送的内容为JSON格式。然后,我们将JSON参数字符串写入输出流,并获取响应。

请注意,这只是一个基本的示例,实际使用时需要进行错误处理、异常处理和适当的数据解析。同时,您可以使用其他第三方库(如Apache HttpClient、OkHttp等)来进行更高级的HTTP请求处理。

标签:
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有