HttpURLConnection 提交POST时,传入的中文参数,到STRUTS接受时,可能会显示为中文,以下几处修改可解决HttpURLConnection POST对URL编码
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionID);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String content = "";
if(params != null){
Set<String> key = params.keySet();
for (Iterator<String> it = key.iterator(); it.hasNext(); ) {
String s = (String)it.next();
content = content + "&" + s + "=" + URLEncoder.encode(params.get(s).toString(), "UTF-8");
}
}
if (content.length() > 1) {
content = content.substring(1);
}
out.writeBytes(content);
out.flush();
out.close();
struts配置文件
<constant name="struts.i18n.encoding" value="UTF-8" />
如果还是不行,则需要对接受的中文参数手动转码
/**
* 根据key获取请求中对应的对象
* @param key 对象对应的key
* @return 请求中的对象
*/
public String getRequestParameter(String key){
try {
String value = getHttpRequest().getParameter(key) ;
if(null == value || value.trim().length() == 0){
return null ;
}
return new String(value.getBytes("iso-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null ;
}
}
经过以上几步,基本可以解决传参乱码问题