Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java调用http接口

作者:城若幻影   发布日期:2026-06-13   浏览:62

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

public class HttpExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    // HTTP GET request
    public static void sendGet(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", USER_AGENT);

            int responseCode = connection.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);

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

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

                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("GET request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // Example usage of sending a GET request to an HTTP endpoint
        sendGet("http://example.com/api/data");
    }
}

解释说明:

  1. 导入必要的包:我们导入了java.iojava.net中的类,用于处理HTTP请求和响应。
  2. 设置User-Agent:为了模拟浏览器访问,设置了User-Agent头信息。
  3. sendGet方法:该方法用于发送HTTP GET请求。它接收一个URL字符串作为参数,打开连接,设置请求方法为GET,并读取响应内容。
  4. 处理响应:如果响应码是200(即HTTP_OK),则读取并打印响应内容;否则,输出错误信息。
  5. main方法:提供了一个示例调用,向http://example.com/api/data发送GET请求。

希望这个示例对你有帮助!

上一篇:java bigdecimal取绝对值

下一篇:java 数组包含

大家都在看

java url decode

java判断是windows还是linux

java原始数据类型

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java常用的设计模式有哪些

java list 查找

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站