首页 > 解决方案 > 如何在Java中阻止字符串被切断

问题描述

我有一个 java 代码来调用一个返回 JWT 令牌作为响应的 REST API。我向 API 发送一个 GET 调用,它会返回一个 JWT 令牌作为响应。令牌返回正常。但是,我注意到令牌正在以某种方式被修剪。

我在网上尝试了所有东西,但似乎没有什么对我有用。下面是我的代码:

try {
    URL url = new URL(proxyService.getProperty("proxy.url") + "/" + sessionToken);
    log.logText("Connection URL: " + url, logLevel);
    String readLine = null;
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream in = ((URLConnection)conn).getInputStream();
        int length = 0;
        StringBuffer response = new StringBuffer();
        byte[] data1 = new byte[1024];
        while (-1 != (length = in.read(data1))) {
            response.append(new String(data1, 0, length));
        }

        log.logText("JSON String Result: " + response.toString(), logLevel);

    }

    conn.disconnect();
} catch(MalformedURLException e) {
    e.printStackTrace();
} catch(IOException e) {
    e.printStackTrace();
}

oauthToken = oauthToken.replaceAll("^\"|\"$", "");
log.logText("OAuth2 Token: " + oauthToken, logLevel);

return oauthToken;

问候,了解更多

标签: javastringmaven

解决方案


您没有将响应值分配给任何东西。我假设您应该将其分配给oauthToken变量。

也请在 finally 子句中关闭 InputStream 实例,否则会导致资源泄漏。


推荐阅读