1.客户端请求服务器,成功后收到乱码。
解决方法:在http请求header中添加:Accept:text/plain;charset=UTF-8
2.POST方法请求参数中带中文
解决方法:web.xml配置filter,编码为UTF-8(某大神及网上:!!!这个只能对POST方法生效,GET方法无用)
3.URL请求中 param 带中文
示例:h ttp://localhost:8080/MySpring/user/test?username=测试 (多个空格不让它成为超链接~)
疑问:这个应该是GET请求,但是经测试,被web.xml中的filter检测并过滤编码了!
解决方法:web.xml配置filter,编码为UTF-8
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String registerUser(@RequestParam("username") String uName) {}
然后得到的username即是正常的中文了
4.Restful风格下,url “路径” 中带中文
解决方法:
客户端对URL参数部分进行URLEncode,编码成UTF-8。
服务器端对其进行相应的URLDecode,解码即可
示例:
@RequestMapping(value = "/userInfo/{province}/{city}/{username}", method = RequestMethod.GET)
@ResponseBody
public String getUserInfo(
@PathVariable("province") String provinceChina,
@PathVariable("city") String cityChina,
@PathVariable("username") String uName) {
}
5.读取文件乱码
CommonsUtils.java
/**
* 简单的获取文件的编码,不做复杂处理
* @param bt
* @return
*/
public static String getFileEncode(CommonsMultipartFile file){
InputStream in;
try {
in = file.getInputStream();
byte[] b = new byte[3];
in.read(b);
in.close();
if (b[0] == -17 && b[1] == -69 && b[2] == -65)
return "UTF-8";
else
return "GBK";
} catch (IOException e) {
// nothing
}
return "UTF-8";
}
示例:
/**
* 从上传的手机文件中提取出手机list
* @return
* @throws InvalidArgumentException
*/
private String getPhonesByUploadFile(CommonsMultipartFile file) throws InvalidArgumentException{
Set<String> phoneSet = new HashSet<>();
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
try {
String charset = CommonsUtils.getFileEncode(file);
inputStream = file.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, charset);
bufferedReader = new BufferedReader(inputStreamReader);
String phone = null;
while ((phone = bufferedReader.readLine()) != null) {
if (!CommonsUtils.isMobile(phone)) {
throw new InvalidArgumentException("phone=" + phone);
}
phoneSet.add(phone);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidArgumentException e) {
throw e;
}finally {
try {
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
} catch (IOException e) {
}
}
if (phoneSet.isEmpty()) {
throw new InvalidArgumentException("文件中的手机列表不能为空");
}
return phoneSet.toString();
}