java篇-java实现url编码与中文的互相转换(乱码问题)

乱码问题

java获取http请后后,处理完成返回给前端时,出现乱码。如代码

@RestController
public class RequestBodyController {
    @RequestMapping("/save")
    public Map content(@RequestBody String content){
        Map<String, Object> map1 = new HashMap<>();

        map1.put("content", content);
        System.out.println(content);
        return map1;
        //http://localhost:8080/save
    }
}

前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>解决乱码</title>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            $("#button1").click(function(){
                $.post("http://localhost:8080/save",
                    {
                        name:"你",
                        age:18,
                    },
                    function(data,status){
                        //data = data.toString()

                        // alert("数据222: \n" + data+ "\n状态: " + status.code);
                        alert(data.content)
                        $("#test1").text(data.content);

                    });
            });
        });

    </script>
</head>
<body>
<button id="button1">发送一个 HTTP post 请求并获取返回结果</button>
<h3 id="test1"></h3>

</body>
</html>

返回结果

问题原因

java在处理请求时,自动转为Base64的编码形式。

需要将前端请求的字符,使用utf-8解码为正常的字符后再处理

如下:content = java.net.URLDecoder.decode(content,"utf-8");

    @RequestMapping("/save")
    public Map content(@RequestBody String content) throws UnsupportedEncodingException {
        Map<String, Object> map1 = new HashMap<>();

        content = java.net.URLDecoder.decode(content,"utf-8");

        System.out.println("content=" + content);
        map1.put("content", content);
        map1.put("xin", "新内容");

        return map1;
        //http://localhost:8080/save
    }

补充:jquery发送的get/post请求默认的编码格式为utf-8

$.get的默认字符编码是urf-8,$.post的默认字符编码是utf-8.

jquery 版本:https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js

java中对url进行编码和解码

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/** 编码Encode后都返回了新的字符串,编码后的字符串不能跨平台,所以要统一制定编码格式
 *  需要注意的是在url中 "\" '&' '=' ':' '/'都是具有特殊意义的符号,这些符号一旦被编译后就会失去本身的
 *  含义,导致无法被解析,
 *  所以在url中需要分块编码,
 *  解码Decoder类中decode方法作用是变回成普通字符,其中加号会变成空格,
 * */
public class testtest {
    public static void main(String[] args) throws UnsupportedEncodingException {
       String url = "http://www.baidu.com?name='张三'&age=18 ";
       String encodeStr = URLEncoder.encode(url,"UTF-8");
        System.out.println(encodeStr);
        System.out.println(URLDecoder.decode(encodeStr,"UTF-8"));

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值