java http token请求代码实例请求代码实例
时间: 2024-09-26 12:10:14 浏览: 38
在Java中发送HTTP请求携带JWT(JSON Web Token)通常会涉及到使用像`HttpURLConnection`, `OkHttpClient`或者第三方库如`Apache HttpClient`或`Spring WebClient`。这里是一个简单的例子,使用`java.net.HttpURLConnection`发送GET请求:
```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class JwtAuthExample {
private static final String ALGORITHM = "HS256";
private static final String SECRET_KEY = "your_secret_key"; // 替换为你的密钥
public static void main(String[] args) throws Exception {
String jwt = generateJwt("username", "password"); // 生成JWT
String url = "https://api.example.com/protected-resource"; // API URL
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// 设置请求头,包含Authorization字段
connection.setRequestProperty("Authorization", "Bearer " + jwt);
connection.setRequestMethod(HttpMethod.GET.name());
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("Success! Response code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println("Response Content: " + content.toString());
} else {
System.out.println("Error: " + responseCode);
}
}
private static String generateJwt(String username, String password) {
try {
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(secretKey);
byte[] encodedData = Base64.getEncoder().encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
byte[] hash = mac.doFinal(encodedData);
return Base64.getEncoder().encodeToString(hash);
} catch (Exception e) {
throw new RuntimeException("Failed to generate JWT", e);
}
}
}
```
阅读全文