我的github
posts - 3243,  comments - 42,  views - 158万

在Java中,你可以使用java.net.HttpURLConnection或者org.apache.http.client.HttpClient来发送GET请求。以下是使用java.net.HttpURLConnection发送带参数的GET请求的示例代码:

复制代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.io.IOException;
 
public class HttpGetRequest {
 
    public static String sendGetRequest(String url, Map<String, String> queryParams) throws IOException {
        StringBuilder urlBuilder = new StringBuilder(url);
        if (queryParams != null && !queryParams.isEmpty()) {
            urlBuilder.append("?");
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            urlBuilder.setLength(urlBuilder.length() - 1); // 移除最后一个"&"
        }
 
        URL obj = new URL(urlBuilder.toString());
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        // 设置请求方法为GET
        con.setRequestMethod("GET");
 
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuilder response = new StringBuilder();
 
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
 
        return response.toString();
    }
 
    public static void main(String[] args) {
        try {
            String url = "http://example.com/api";
            Map<String, String> queryParams = Map.of("param1", "value1", "param2", "value2");
            String response = sendGetRequest(url, queryParams);
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
复制代码

在这个例子中,sendGetRequest方法接受一个URL和一个参数Map,然后构建URL,并发送GET请求。返回的响应会被读取并返回。main方法展示了如何调用这个方法。

参考:百度AI

posted on   XiaoNiuFeiTian  阅读(368)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2023-06-10 C++有限元程序开发
2021-06-10 ogr2ogr导入gpx
2021-06-10 postgis之ST_Dump以及Blob二进制解码
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示