为了账号安全,请及时绑定邮箱和手机立即绑定

将 Jersey 客户端转换为 HttpUrlConnection

将 Jersey 客户端转换为 HttpUrlConnection

PIPIONE 2023-03-17 10:34:43
我有一个从 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。我错过了什么,或者我做错了什么?
查看完整描述

1 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

问题已解决。代码按原样工作。

问题是我缺少 json 值字符串的引号

本来应该

String input = "{\"username\":\"user\",\"password\":\"password\"}";


查看完整回答
反对 回复 2023-03-17
  • 1 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信