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

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