gpt4 book ai didi

java - 字符串字符编码

转载 作者:行者123 更新时间:2023-11-30 08:27:56 25 4
gpt4 key购买 nike

We developed a specific exporter for them which allows the position based product to provide a type of portfolio snapshot - both for equities and fixed income portfolios.

We developed a specific exporter for them which allows the position based product to provide a type of portfolio snapshot – both for equities and fixed income portfolios.

第一个文本是我从 Jira 复制的,第二个是在 Cognity 中打印的。我通过 REST API 从 Jira 获取 JSON 格式的文本,并使用字符串生成器对其进行格式化,最后返回一个普通字符串作为输出。 "' - 等所有符号都没有正确打印,我在输出文本中得到了很多 。我该如何解决?我正在考虑是否可以通过某种方式更改输出字符串的编码,也许这可行?

编辑:这就是我用来从 Jira 获取信息的方式,之后我从返回的 JSON 中提取我想要的内容。

   String usercreds = "?os_username=user&os_password=password";
try {
url = new URL("http://jira/rest/api/2/issue/" + issuekey + usercreds);

URLConnection urlConnection = url.openConnection();

if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}

InputStream inputStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((s = reader.readLine()) != null) {
temp.append(s);
s = "";
}
issue = new JSONObject(temp.toString());
temp.setLength(0);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

如果我理解正确,应该有一种方法可以让我指定我希望输出为 ("application/json;charset=utf-8") 这段代码中的某处可能会解决我的问题?

最佳答案

JSON 响应中的破折号是 U+2013 (EN DASH。) 当编码为 UTF-8 时,if 形成字节序列 e2 80 93。此数据正在使用错误的编码进行解码(很可能是 windows-1252。)Java 的默认 I/O 编码是系统相关的。

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

以上线路有问题。您必须指定 encoding使用 InputStreamReader 进行转码时。

例如:

  public static void readUtf8(URLConnection connection, Appendable out)
throws IOException {
CharBuffer buffer = CharBuffer.allocate(1024);
try (InputStream in = connection.getInputStream();
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
while (reader.read(buffer) != -1) {
buffer.flip();
out.append(buffer);
buffer.clear();
}
}
}

注意:从技术上讲,JSON 可以是任何 Unicode 编码(不仅仅是 UTF-8)- 如果您需要处理读取 this .

注意 2:自 Java 5 以来,HttpUrlConnection 似乎有所改进,但我会确保它进行自动长度处理(读取 Content-Length header /处理分块编码/等)

关于java - 字符串字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20521327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com