以下是Java代码发送带参数的GET请求,并设置连接超时和读取超时时间的示例:

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

public class GetRequestExample {
    public static void main(String[] args) {
        String url = "https://example.com/api";
        String param1 = "param1Value";
        String param2 = "param2Value";
        int connectTimeout = 5000; // 5 seconds
        int readTimeout = 10000; // 10 seconds

        try {
            // Build URL with parameters
            URL apiUrl = new URL(url + "?param1=" + param1 + "&param2=" + param2);

            // Open connection and set timeouts
            HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);

            // Set request method
            conn.setRequestMethod("GET");

            // Send request
            conn.connect();

            // Read response
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Print response
            System.out.println(response.toString());

        } catch (IOException e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

在这个例子中,我们使用URL连接对象(HttpURLConnection)打开连接,并设置连接超时和读取超时时间。我们通过将参数附加到URL中来构建GET请求。我们设置请求方法为GET,然后通过调用connect()方法发送请求。最后,我们读取响应并将其打印出来。

请注意,这个例子中的连接超时和读取超时时间只是示例。您应该根据您的应用程序的需要选择适当的超时时间

java代码发送带参数的get请求并且设置连接超时和读取超时时间

原文地址: https://www.cveoy.top/t/topic/cyV3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录