java Struts2 使用HttpURLConnection进行post提交乱码

加上 urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 即可解决


 private HttpRespons send(String urlString, String method,
            Map<String, String> parameters, Map<String, String> propertys)
            throws IOException {
        HttpURLConnection urlConnection = null;

        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(0x2710);
        urlConnection.setRequestMethod(method);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        
        urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        if (propertys != null) {
            for (String key : propertys.keySet()) {
                urlConnection.addRequestProperty(key, propertys.get(key));
            }
        }

        if (method.equalsIgnoreCase("POST") && parameters != null) {
            StringBuilder param = new StringBuilder();
            for (String key : parameters.keySet()) {
                param.append(key).append("=").append(parameters.get(key));
                param.append("&");
            }
            urlConnection.getOutputStream().write(
                    param.toString()
                    .substring(0, param.toString().length() - 1)
                    .getBytes(defaultContentEncoding));
            urlConnection.getOutputStream().flush();
            urlConnection.getOutputStream().close();
        }

        return this.makeContent(urlString, urlConnection);
    }

猜你喜欢

转载自yx200404.iteye.com/blog/2307661
今日推荐