java获取微信小程序二维码乱码

最开始乱码,用String接受的微信返回值,发现不能用字符串接受,用输入流转字节,再转base64传给前端

public String xyhkQrCode(HttpServletRequest request, HttpServletResponse response, String path, String scene) {
        PKWXConfig pkwxConfig = new PKWXConfig();
        String token = getToken(pkwxConfig.getStuAppID(), pkwxConfig.getStuKey());
        return genQrCode(token,path,scene);
    }

    private String genQrCode(String token,String path,String scene){
        String url = WechatUtil.WX_ACODE_UN_LIMIT.replace("ACCESS_TOKEN", token);
        JSONObject paramJson=new JSONObject();
        paramJson.put("page",path);
        paramJson.put("scene",scene);
        //返回值不能使用String接受
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        //创建httpClient连接对象
        httpClient = HttpClients.createDefault();
        //创建post请求连接对象
        HttpPost httpPost = new HttpPost(url);
        //创建连接请求对象,并设置连接参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)   //连接服务区主机超时时间
                .setConnectionRequestTimeout(60000) //连接请求超时时间
                .setSocketTimeout(60000).build(); //设置读取响应数据超时时间
        //为httppost请求设置参数
        httpPost.setConfig(requestConfig);
        //将上传参数放到entity属性中
        httpPost.setEntity(new StringEntity(JSON.toJSONString(paramJson), "UTF-8"));
        //添加头信息
        httpPost.addHeader("Content-type", "text/xml");
        String result = "";
        try {
            //发送请求
            httpResponse = httpClient.execute(httpPost);
            //从相应对象中获取返回内容
            HttpEntity entity = httpResponse.getEntity();
            InputStream content = entity.getContent();
            byte[] bytes = InputStreamToByte(content);
            result = Base64.encodeBase64String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 输入流转字节流
     * */
    private byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int ch;
        while ((ch = in.read(buffer)) != -1) {
            bytestream.write(buffer,0,ch);
        }
        byte data[] = bytestream.toByteArray();
        bytestream.close();
        return data;
    }

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章