https请求发送java代码
时间: 2024-09-19 20:13:38 浏览: 37
在Java中,发送HTTPS请求通常使用`HttpURLConnection`、`OkHttpClient`或者第三方库如`Apache HttpClient`或`Retrofit`等。这里以`HttpURLConnection`为例展示如何发送GET请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
// 创建URL对象
URL url = new URL("https://example.com/api/data");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 设置请求方法为GET
connection.setUseCaches(false); // 禁止缓存
// 添加身份验证信息(如果需要)
String auth = "username:password";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes()); // 编码成Base64
connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuth));
// 连接建立成功,状态码为200表示成功
if (connection.getResponseCode() == 200) {
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
} else {
System.err.println("Request failed with status code: " + connection.getResponseCode());
}
// 关闭连接
connection.disconnect();
}
}
```
阅读全文