如何在Java中阻止字符串被截断



我有一个java代码来调用一个REST API,它返回一个JWT令牌作为响应。我向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;

问候,nasa

如@markspace所述,请指定oauthToken的数据类型(我认为是String类型)。打印总字符串,然后是replaceALL之前和replaceALL之后的长度。比较replace添加的总长度,如果是,则没有字符串被修剪的问题。

您没有将响应值分配给任何东西。我认为你应该分配它给oauthToken变量。

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

我认为你必须先关闭InputStream,以刷新内部缓冲区。

public static String getOauthToken() throws IOException {
URL url = new URL(proxyService.getProperty("proxy.url") + "/" + sessionToken);
log.logText("Connection URL: " + url, logLevel);
String oauthToken = readInputString(url);
oauthToken = oauthToken.replaceAll("^"|"$", "");

log.logText("OAuth2 Token: " + oauthToken, logLevel);
return oauthToken;
}
private static String readInputString(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
throw new RuntimeException("Not expected response code");
try (InputStream in = conn.getInputStream()) {
StringBuffer buf = new StringBuffer();
byte[] b = new byte[1024];
while (true) {
int readBytes = in.read(b);
if (readBytes == -1)
break;
buf.append(new String(b, 0, readBytes));
}
log.logText("JSON String Result: " + buf, logLevel);
return buf.toString();
}
}

看起来我调用的实际应用程序正在切断响应值。我缩短了JWT令牌的长度,它没有把它切断。出于性能原因,应用程序必须对字符串中允许的最大字符数进行限制。

最新更新