我有一条短信/字符串,其中包含 ä、ü、ß 等字母。我希望所有内容都采用 UTF-8 编码。当我写入文件或将字符串打印到控制台时,一切都很好。但是,当我想将相同的字符串发送到 Web 服务时,我得到的不是 ä,ü,ß
,而是以下 �
我从 Servlet 读取该文件。
我真的必须使用以下 2 行来获取 UTF-8 编码的文本吗?
byte [] bray = text.getBytes("UTF-8");
text = new String(bray);
.
public static String readAsStream_UTF8(String filePathName){
String text ="";
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/"+filePathName);
if(input == null){
System.out.println("Inputstream null.");
}else{
InputStreamReader isr = null;
try {
isr = new InputStreamReader((InputStream)input, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String sCurrentLine;
while ((sCurrentLine = reader.readLine()) != null) {
sb.append(sCurrentLine);
}
text= sb.toString();
//it works only if I use the following 2 lines
byte [] bray = text.getBytes("UTF-8");
text = new String(bray);
} catch (Exception e1) {
e1.printStackTrace();
}
}
return text;
}
我的 sendPOST 方法如下所示:
String charset = "UTF-8";
OutputStreamWriter writer = null;
HttpURLConnection con = null;
String response_txt ="";
InputStream iss = null;
try {
URL url = new URL(urlService);
con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true); //triggers POST
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("accept-charset", charset);
//con.setRequestProperty("Content-Type", "application/soap+xml");
con.setRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8");
writer = new OutputStreamWriter(con.getOutputStream());
writer.write(msg); //send POST data string
writer.flush();
writer.close();
我需要做什么才能强制将发送到 Web 服务的消息真正采用 UTF-8 编码。
最佳答案
如果您知道要发送的文件的编码,则无需将其转换为中间字符串。只需将其字节复制到输出即可:
// inputstream to a UTF-8 encoded resource file
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/"+filePathName);
HttpURLConnection con = ...
// set contenttype and encoding
con.setRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8");
// copy input to output
copy(in, con.getOutputStream());
使用一些copy功能。
此外,您还可以将 Content-Length
header 设置为资源文件的大小。
关于java - 如何保证java POST请求字符串/文本是UTF-8编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32457972/