java使用http请求-添加请求头headers
·
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// 定义请求 URL
String url = "https://example.com/api/resource";
// 创建 URL 对象
URL apiUrl = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 添加身份验证信息到请求头
String username = "yourUsername";
String password = "yourPassword";
String credentials = username + ":" + password;
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
// 获取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应
System.out.println("Response: " + response.toString());
} else {
System.out.println("Error: " + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)