我有一个Jersey客户端,可以从API检索jwt令牌。

这是代码

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());
    os.flush();

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
           + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();

} catch (IOException e) {
}


我的问题是我无法将.post(ClientResponse.class, sb.toString())转换为HttpUrlConnection。

我缺少什么,或者我做错了什么?

谢谢

最佳答案

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

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

本来应该

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

关于java - 将Jersey客户端转换为HttpUrlConnection,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56959220/

10-13 09:36