您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
要使用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);
// 打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法(GET或POST)
connection.setRequestMethod("GET");
// 设置请求属性
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应码
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"; // 替换为您要请求的URL
String response = sendHttpRequest(urlString);
System.out.println("HTTP Response: " + response);
}
这个示例展示了如何使用Java的HttpURLConnection
类发送GET请求并解析HTTP响应。如果您需要处理更复杂的HTTP请求(如POST请求、设置请求头等),可以考虑使用Apache HttpClient或OkHttp库。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。