HttpURLConnection与Struts交互传参乱码问题

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 ;
		}
	}


经过以上几步,基本可以解决传参乱码问题



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值