Java 发送authorization bearer
时间: 2023-09-28 21:05:42 浏览: 61
在Java中发送Authorization Bearer,可以通过设置HTTP请求头来实现。具体步骤如下:
1. 创建HTTP连接对象
```
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
```
2. 设置请求方法为GET或POST等
```
connection.setRequestMethod("GET");
```
3. 设置Authorization Bearer
```
String token = "your_token_here";
connection.setRequestProperty("Authorization", "Bearer " + token);
```
4. 发送请求并获取响应
```
int responseCode = connection.getResponseCode();
InputStream inputStream = connection.getInputStream();
```
完整的代码示例:
```
import java.io.*;
import java.net.*;
public class AuthorizationBearerExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
String token = "your_token_here";
connection.setRequestProperty("Authorization", "Bearer " + token);
int responseCode = connection.getResponseCode();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
System.out.println("Response Code : " + responseCode);
System.out.println("Response : " + response.toString());
}
}
```