Java http请求携带token
时间: 2023-10-12 21:06:08 浏览: 123
在 Java 中发送 HTTP 请求并携带 token 可以通过添加 HTTP 头部信息来实现。具体的做法是:
1. 创建一个 `HttpURLConnection` 对象,并设置请求的 URL。
```java
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
```
2. 添加 HTTP 头部信息,其中 Authorization 头部用于携带 token。
```java
String token = "your_token_here";
connection.setRequestProperty("Authorization", "Bearer " + token);
```
3. 发送请求并获取响应。
```java
connection.setRequestMethod("GET"); // 设置请求方法,例如 GET、POST 等
int responseCode = connection.getResponseCode(); // 获取响应状态码
String responseBody = ""; // 响应正文
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseBody += line;
}
}
```
完整的代码示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpWithToken {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String token = "your_token_here";
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
String responseBody = "";
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseBody += line;
}
}
System.out.println("Response code: " + responseCode);
System.out.println("Response body: " + responseBody);
}
}
```
阅读全文
相关推荐


















