我有一个从 API 检索 jwt 令牌的 Jersey 客户端。
这是代码
public static final String INFO_ENDPOINT = "http://10.1.9.10:7100/Info/";
private static final String INFO_USERNAME = "user";
private static final String INFO_PASSWORD = "password";
private static final String AUTH_PATH = "auth";
private String token;
private final Client client;
public JerseyClient() {
ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(MultiPartWriter.class);
client = Client.create(cc);
}
public void authenticate() {
try {
WebResource resource = client.resource(INFO_ENDPOINT + AUTH_PATH);
StringBuilder sb = new StringBuilder();
sb.append("{\"username\":\"" + INFO_USERNAME + "\",");
sb.append("\"password\":\"" + INFO_PASSWORD + "\"}");
ClientResponse clientResp = resource.type("application/json")
.post(ClientResponse.class, sb.toString());
String content = clientResp.getEntity(String.class);
System.out.println("Response:" + content);
token = content.substring(content.indexOf("\"token\":") + 9,
content.lastIndexOf("\""));
System.out.println("token " + token);
} catch (ClientHandlerException | UniformInterfaceException e) {
}
}
上面的代码返回一个 jwt 令牌,然后用作另一个调用的密钥。
我正在尝试将其转换为使用 HttpUrlConnection。但这似乎不起作用
这是我试过的。它不会给出错误,但也不返回令牌。响应为空
try {
URL url = new URL("http://10.1.9.10:7100/Info/auth");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("accept", "application/json");
String input = "{\"username\":user,\"password\":\"password\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
}
我的问题是我无法转换.post(ClientResponse.class, sb.toString()) 为 HttpUrlConnection。
我错过了什么,或者我做错了什么?
一只甜甜圈
相关分类