您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
要使用 Java 程序连接 HTTP 服务器,您可以使用 java.net.HttpURLConnection
类或者第三方库如 Apache HttpClient 或者 OkHttp
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public static String sendHttpRequest(String urlString) {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
// 创建 URL 对象
URL url = new URL(urlString);
// 打开连接并强制转换为 HttpURLConnection
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
connection.setRequestMethod("GET");
// 设置接受输入流的属性
connection.setReadTimeout(10000);
connection.setConnectTimeout(10000);
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 根据响应码判断请求是否成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} else {
System.out.println("GET request failed");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
public static void main(String[] args) {
String urlString = "https://api.example.com/data";
String response = sendHttpRequest(urlString);
System.out.println("Server response: " + response);
}
这个示例展示了如何使用 Java 标准库中的 HttpURLConnection
类发起一个简单的 HTTP GET 请求。请注意,这个示例没有处理异常和错误情况,实际应用中可能需要更详细的错误处理。如果您需要更高级的功能,可以考虑使用 Apache HttpClient 或 OkHttp 等第三方库。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。