微信公众好获取用户信息之头像显示

编码问题 微信api接口里来的数据类似这种:

http:\/\/wx.qlogo.cn\/mmopen\/vi_32\/VMFIw6BYW51AFPAF7YWcz4yvfb3btnkicOgUoBzxKibQzibicSCJibiaDW8xYnQaWKOPnSVElP9xr1RV7h77ZSvEef0g\/0

处理方法:

private UserInfo getBaseUserInfo(String access_token, String openid) {
            // 接口示例  https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
            String url = "https://api.weixin.qq.com/sns/userinfo";
            String param = "access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
            String res = NetConnect.sendGet(url, param);
            System.out.println("用户信息:"+res);
            //{"openid":"okACkjoQAHs0-Gh8tDNc5sHhgDxx","nickname":"波子汽水","sex":1,"language":"zh_CN","city":"岳阳","province":"湖南","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/vi_32\/VMFIw6BYW51AFPAF7YWcz4yvfb3btnkicOgUoBzxKibQzibicSCJibiaDW8xYnQaWKOPnSVElP9xr1RV7h77ZSvEef0g\/0","privilege":[],"unionid":"oKVCRwEqWE7hLWI8kfBy8-sAu4xx"}
            //{"openid":"okACkjjb2YTF0mO7kRcKLNVzKvxx","nickname":"MAY","sex":2,"language":"zh_CN","city":"深圳","province":"广东","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/vi_32\/PibRCemxjD5SfY9e8MXwy0BYjwbtO9UicMGm0kzRbEmg4o2ib7iaNcR4NAfHlxHlw0D6x0CDVjxDwOCh45VNZicVfYg\/0","privilege":[],"unionid":"oKVCRwEgk83_E1bnXFaT4urGtkxx"}
            UserInfo u = new UserInfo();
            if(res!=null && res.length()>0){ 
                String dataimg = "images/head.png";
                try {
                    dataimg = java.net.URLEncoder.encode(getValue(res,"headimgurl").replaceAll("\\\\", ""), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                u.setHeadImgurl(dataimg); 
                u.setNickName(getValue(res,"nickname"));
                u.setOpenid(getValue(res,"openid"));
            }
            return u;
        }

  String path = "GDearlyWarning/personalCenter.html?openid="+openid+"&headimgurl="+u.getHeadImgurl()+"&nickname="+URLEncoder.encode(u.getNickName(), "UTF-8");
                 System.out.println("传送前台页面:"+path);
                 response.sendRedirect(path);

页面处理:

var headImgurl = getQueryString("headimgurl");
    var u=decodeURI(headImgurl);
        $("#headImg").html("<img src="+u+" width=100%>");

遇到中文乱码问题
页面地址:

http://xx.cn/MobileWeather/GDearlyWarning/personalCenter.html?openid=okACkjmr3EHNEQKVO0dqTvDrxx&headimgurl=http%3A%2F%2Fwx.qlogo.cn%2Fmmopen%2Fvi_32%2FDbvcBGEzm0J4Dmv2WmB9o5wO5pcGibCgJePibL60csMib5tXjtumaxWicB9QB77hTJY4rchdMU6HogOZRDzccoxvyw%2F0&nickname=%E6%B3%A2%E5%AD%90%E6%B1%BD%E6%B0%B4

这个昵称乱码 查到

function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null){
            return unescape(r[2]);
        }
        return null;
    }

返回的已经用unescape解码了所以乱码了

头像使用unescape之后又 decodeURI 一次 可能是因为头像路径全是英文字符所以不受影响

相关文章
相关标签/搜索