Java https请求 需要获取token 携带header 需要账号和密码 怎么写
时间: 2024-03-26 10:39:07 浏览: 75
你可以使用 Java 中的 HttpURLConnection 类来发送 HTTPS 请求,并在请求中添加 Header。
下面是一个示例代码,其中我们使用 Base64 编码来将账号和密码组成的字符串转换为 Authorization Header 中的值。
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class HttpsRequestExample {
public static void main(String[] args) throws IOException {
String username = "your_username";
String password = "your_password";
// create URL
URL url = new URL("https://example.com/api");
// create connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// set request method
connection.setRequestMethod("GET");
// set authorization header
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
String authHeaderValue = "Basic " + new String(encodedAuth);
connection.setRequestProperty("Authorization", authHeaderValue);
// send request
int responseCode = connection.getResponseCode();
// read response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print response
System.out.println("Response code: " + responseCode);
System.out.println("Response body: " + response.toString());
}
}
```
在上面的代码中,你需要替换掉 `your_username` 和 `your_password` 为你自己的账号和密码。然后你就可以使用 `connection.setRequestProperty` 方法来添加任意的 Header。
请注意,上述示例中的请求方法是 GET,你可以根据你的需要更改为 POST 或其他 HTTP 方法。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)