温馨提示×

如何在Java中设置GET请求的参数

小樊
125
2024-08-12 22:06:40
栏目: 编程语言

在Java中设置GET请求的参数可以通过构建URL,并在URL中添加参数。下面是一个简单的示例代码:

import java.net.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            String urlString = "http://example.com/api";
            String param1 = "key1=value1";
            String param2 = "key2=value2";

            URL url = new URL(urlString + "?" + param1 + "&" + param2);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            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.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们首先构建了一个URL对象,将参数拼接在URL后面。然后使用HttpURLConnection打开连接,并设置请求方法为GET。最后读取响应内容并输出。

0