java代码发get请求
以下是一个使用Java发出GET请求的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequest {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/resource");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
conn.setRequestMethod("GET");
// 设置连接超时时间
conn.setConnectTimeout(5000);
// 设置读取超时时间
conn.setReadTimeout(5000);
// 发送GET请求
conn.connect();
// 获取响应状态码
int responseCode = conn.getResponseCode();
// 如果响应状态码为200,则表示请求成功
if (responseCode == 200) {
// 获取响应数据
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应数据
System.out.println(response.toString());
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
// 断开连接
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在该示例代码中,我们使用了Java的HttpURLConnection类来发送GET请求。其中,我们设置了请求方法为GET,连接超时时间为5秒,读取超时时间为5秒。我们还获取了响应状态码,并根据状态码来判断请求是否成功。如果响应状态码为200,则表示请求成功,我们就可以获取响应数据并输出。最后,我们断开了与服务器的连接
原文地址: https://www.cveoy.top/t/topic/cvVI 著作权归作者所有。请勿转载和采集!