发送'+'字符utf-8,java App到servlet

时间:2016-03-10 23:34:48

标签: java servlets utf-8 httpurlconnection

我正在尝试编写一个包含这种字符串的字节缓冲区    &安培; FIELD_VALUE =

kggsW9YizUuRpjB/RtppZImnC8SekMGAWGnCmw+wPMwn7fWJva0QbSK/Slt/DDsZ

通过HttpURLConnection,但我收到& field_Value =

kggsW9YizUuRpjB/RtppZImnC8SekMGAWGnCmw wPMwn7fWJva0QbSK/Slt/DDsZ

所以'+'是唯一没有发送的字符。它发生在我的所有字符串里面都包含一个'+'。

你能告诉我如何编码字符串或我做错了什么。

这是我的代码:

发信人:

url = new URL(url_globalApp);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Language", "en-US");  
        connection.setRequestProperty("Accept-Charset", "UTF-8"); 
        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());
        //**************** first try ************//
        wr.write(pairs_1.getBytes("UTF-8"), 0, pairs_1.length());

        //**************** second try ************//
            //wr.writeBytes(new String(pairs_1.getBytes(),"UTF-8"));

        //**************** third try ************//
            //wr.writeUTF(pairs_1);
            wr.flush ();
            wr.close ();

的Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    Map <String,String[]> parameters = request.getParameterMap();
    System.out.println(parameters.get("field_value_1")[0]);

1 个答案:

答案 0 :(得分:0)

查询参数的值必须进行URL编码。

的网址编码
kggsW9YizUuRpjB/RtppZImnC8SekMGAWGnCmw+wPMwn7fWJva0QbSK/Slt/DDsZ

kggsW9YizUuRpjB%2FRtppZImnC8SekMGAWGnCmw%2BwPMwn7fWJva0QbSK%2FSlt%2FDDsZ

请注意/如何编码为%2F+编码为%2B

你可以通过调用

来实现
java.net.URLEncoder.encode("kggsW9YizUuRpjB/RtppZImnC8SekMGAWGnCmw+wPMwn7fWJva0QbSK/Slt/DDsZ", "UTF-8")