【发布时间】:2015-09-08 12:32:41
【问题描述】:
我有一个带有 ä,ü,ß 等字母的短信/字符串。我希望所有内容都采用 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 服务的 msg 真正进行 UTF-8 编码。
【问题讨论】:
-
你为什么不使用
OutputStreamWriter的构造函数,它带有一个字符集名称,即writer = new OutputStreamWriter(con.getOutputStream(), "utf-8");? -
即使你使用 UTF-8 编写消息,WS 是否使用 UTF-8 读取它?也许问题出在另一边?是否确认 WS 正确处理 UTF-8?
-
hmm 看起来这是解决方案: writer = new OutputStreamWriter(con.getOutputStream(), "utf-8");可以发个答案吗?
标签: java servlets post encoding utf-8