微信小程序 获取对应页面二维码

获取二维码流程如下,重新整理总结:(java)

 转自 :http://www.wxapp-union.com/forum.php?mod=viewthread&tid=3584&extra=

1.后台向微信发送请求,返回的为图片流

2.将微信返回的图片保存到服务器

3.将图片的地址返回到前台

4.前台处理就相当于处理 获取服务器的普通图片文件

如果图片有文件

但是提示格式不对或太大等 将文件格式转为txt 看看返回的信息

可能是token失效(2个小时) ,参数传递失败等


HttpClientConnectionManager 自定义工具类

扫描二维码关注公众号,回复: 724973 查看本文章
[java] view plain copy
  1.  package cn.edu.hbcf.plugin.wx.utils;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.URL;  
  10. import java.net.URLConnection;  
  11. import java.net.URLEncoder;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14. import org.apache.http.HttpEntity;  
  15. import org.apache.http.HttpResponse;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.entity.StringEntity;  
  18. import org.apache.http.impl.client.DefaultHttpClient;  
  19. import org.apache.http.message.BasicHeader;  
  20. import org.apache.http.protocol.HTTP;  
  21.    
  22. public class HttpClientConnectionManager {  
  23.     /** 
  24.      * @param reqUrl 
  25.      *            基础的url地址 
  26.      * @param params 
  27.      *            查询参数 
  28.      * @return 构建好的url 
  29.      */  
  30.            
  31.        
  32.     public static String httpPostWithJSON(String url, String json,String id)  
  33.             throws Exception {  
  34.         String result = null;  
  35.         // 将JSON进行UTF-8编码,以便传输中文  
  36.         String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);   
  37.         DefaultHttpClient httpClient = new DefaultHttpClient();  
  38.         HttpPost httpPost = new HttpPost(url);  
  39.         httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");    
  40.         StringEntity se = new StringEntity(json);  
  41.         se.setContentType("application/json");  
  42.         se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));  
  43.         httpPost.setEntity(se);  
  44.         // httpClient.execute(httpPost);  
  45.         HttpResponse response = httpClient.execute(httpPost);  
  46.         if (response != null) {  
  47.             HttpEntity resEntity = response.getEntity();  
  48.             if (resEntity != null) {  
  49.                 InputStream instreams = resEntity.getContent();   
  50.                // ResourceBundle systemConfig = ResourceBundle.getBundle("config/system", Locale.getDefault());  
  51.               //  String uploadSysUrl = systemConfig.getString("agentImgUrl")+id+"/";  
  52.               //  File saveFile = new File(uploadSysUrl+id+".jpg");  
  53.                 String uploadSysUrl = "D:\\upload"+"/";  
  54.                 File saveFile = new File(uploadSysUrl+id+".jpg");  
  55.                    // 判断这个文件(saveFile)是否存在  
  56.                    if (!saveFile.getParentFile().exists()) {  
  57.                        // 如果不存在就创建这个文件夹  
  58.                        saveFile.getParentFile().mkdirs();  
  59.                    }  
  60.                 saveToImgByInputStream(instreams, uploadSysUrl, id+".jpg");  
  61.             }  
  62.         }  
  63.         return result;  
  64.     }   
  65.        
  66.     /* @param instreams 二进制流 
  67.     * @param imgPath 图片的保存路径 
  68.     * @param imgName 图片的名称 
  69.     * @return 
  70.     *      1:保存正常 
  71.     *      0:保存失败 
  72.     */  
  73.    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName) throws FileNotFoundException{  
  74.     
  75.        int stateInt = 1;  
  76.        File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等  
  77.        FileOutputStream fos=new FileOutputStream(file);  
  78.        if(instreams != null){  
  79.            try {  
  80.                                    
  81.                byte[] b = new byte[1024];  
  82.                int nRead = 0;  
  83.                while ((nRead = instreams.read(b)) != -1) {  
  84.                    fos.write(b, 0, nRead);  
  85.                }  
  86.                                 
  87.            } catch (Exception e) {  
  88.                stateInt = 0;  
  89.                e.printStackTrace();  
  90.            } finally {  
  91.                  
  92.                try {  
  93.                    fos.flush();  
  94.                    fos.close();  
  95.             } catch (IOException e) {  
  96.                 e.printStackTrace();  
  97.             }   
  98.            }  
  99.        }  
  100.        return stateInt;  
  101.    }        
  102.    public static boolean exists(String imgPath){  
  103.        File saveFile = new File(imgPath);  
  104.        if (!saveFile.getParentFile().exists()) {  
  105.            return false;  
  106.        }else{  
  107.            //如果存在判断这个文件的大小  
  108.            if(saveFile.length()>0){  
  109.                System.out.println("--------------------------------"+saveFile.length());  
  110.                return true;  
  111.            }else{  
  112.                return false;  
  113.            }  
  114.        }  
  115.        
  116.    }        
  117.    /** 
  118.     * 向指定URL发送GET方法的请求 
  119.     *  
  120.     * @param url 
  121.     *            发送请求的URL 
  122.     * @param param 
  123.     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
  124.     * @return URL 所代表远程资源的响应结果 
  125.     */  
  126.    public static String sendGet(String url, String param) {  
  127.        String result = "";  
  128.        BufferedReader in = null;  
  129.        try {  
  130.            String urlNameString = url + "?" + param;  
  131.            System.out.println(urlNameString+"........");  
  132.            URL realUrl = new URL(urlNameString);  
  133.            // 打开和URL之间的连接  
  134.            URLConnection connection = realUrl.openConnection();  
  135.            // 设置通用的请求属性  
  136.            connection.setRequestProperty("accept""*/*");  
  137.            connection.setRequestProperty("connection""Keep-Alive");  
  138.            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  139.            // 建立实际的连接  
  140.            connection.connect();  
  141.            // 获取所有响应头字段  
  142.            Map<String, List<String>> map = connection.getHeaderFields();  
  143.            // 遍历所有的响应头字段  
  144.            for (String key : map.keySet()) {  
  145.                System.out.println(key + "--->" + map.get(key));  
  146.            }  
  147.            // 定义 BufferedReader输入流来读取URL的响应  
  148.            in = new BufferedReader(new InputStreamReader(  
  149.                    connection.getInputStream()));  
  150.            String line;  
  151.            while ((line = in.readLine()) != null) {  
  152.                result += line;  
  153.            }  
  154.        } catch (Exception e) {  
  155.            System.out.println("发送GET请求出现异常!" + e);  
  156.            e.printStackTrace();  
  157.        }  
  158.        // 使用finally块来关闭输入流  
  159.        finally {  
  160.            try {  
  161.                if (in != null) {  
  162.                    in.close();  
  163.                }  
  164.            } catch (Exception e2) {  
  165.                e2.printStackTrace();  
  166.            }  
  167.        }  
  168.        return result;  
  169.    }  
  170.    
  171.      
  172.      
  173.    public static Object httpPostWithJSON2(String url, String json,String id)  
  174.            throws Exception {  
  175.        // 将JSON进行UTF-8编码,以便传输中文  
  176.        InputStream instreams = null;  
  177.        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);   
  178.        DefaultHttpClient httpClient = new DefaultHttpClient();  
  179.        HttpPost httpPost = new HttpPost(url);  
  180.        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");    
  181.        StringEntity se = new StringEntity(json);  
  182.        se.setContentType("application/json");  
  183.        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));  
  184.        httpPost.setEntity(se);  
  185.        // httpClient.execute(httpPost);  
  186.        HttpResponse response = httpClient.execute(httpPost);  
  187.        if (response != null) {  
  188.            HttpEntity resEntity = response.getEntity();  
  189.            if (resEntity != null) {  
  190.                 instreams = resEntity.getContent();   
  191.                
  192.            }  
  193.        }  
  194.        return instreams;  
  195.    }  
  196.       
  197. }  

调用工具类中的方法 获取图片  参数需要前台传给

[java] view plain copy
  1. /** 
  2.      *  获取微信二维码 
  3.      * @param path 
  4.      * @param width 二维码的宽度 
  5.      * @param access_token  
  6.      * @return 
  7.      */  
  8.     @RequestMapping(value = "/createwxaqrcode")  
  9.     @ResponseBody  
  10.     public Object  createwxaqrcode(String access_token,String path,String width, String id ){  
  11.         AgentDTO agentDTO = new AgentDTO();  
  12.         String URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode";    
  13.         //二维码图片位置  
  14.         String agentImgDownloadUrl = "D:\\upload";  
  15.         try {    
  16.             AgentReqView agentResView = new AgentReqView();  
  17.             Map<String, Object> map = new HashMap<String, Object>();  
  18.             map.put("path", path);  
  19.             map.put("width", width);  
  20.             JSONObject json = JSONObject.fromObject(map);  
  21.             HttpClientConnectionManager.httpPostWithJSON(URL+"?access_token="+ access_token, json.toString(),id );  
  22.             String downloadUrl = agentImgDownloadUrl+ id+  "/";  
  23.             //返回给前端的后台服务器文件下载路径  
  24.             String downloadfileUrl = downloadUrl + id + ".jpg";  
  25.             agentResView.setDownloadfileUrl(downloadfileUrl);  
  26.             agentDTO.setResultCode("200");  
  27.             agentDTO.setDesc("成功");  
  28.             agentDTO.setBody(agentResView);  
  29.         } catch (Exception e) {    
  30.             e.printStackTrace();    
  31.         }  
  32.         return agentDTO;  
  33.     }  

以下为返回值格式定义,可自由定义

[java] view plain copy
  1. import java.util.List;  
  2.   
  3. public class AgentDTO {  
  4.     private String resultCode;  
  5.     private String desc;  
  6.     private AgentReqView body;  
  7.       
  8.     public AgentDTO (){  
  9.           
  10.     }  
  11.       
  12.     public AgentDTO (String resultCode,String desc){  
  13.         this.setResultCode(resultCode);  
  14.         this.setDesc(desc);  
  15.           
  16.     }  
  17.     public String getResultCode() {  
  18.         return resultCode;  
  19.     }  
  20.     public void setResultCode(String resultCode) {  
  21.         this.resultCode = resultCode;  
  22.     }  
  23.     public String getDesc() {  
  24.         return desc;  
  25.     }  
  26.     public void setDesc(String desc) {  
  27.         this.desc = desc;  
  28.     }  
  29.   
  30.     public AgentReqView getBody() {  
  31.         return body;  
  32.     }  
  33.   
  34.     public void setBody(AgentReqView body) {  
  35.         this.body = body;  
  36.     }  
  37.       
  38.   
  39.       
  40. }  

[java] view plain copy
  1. public class AgentReqView {  
  2.   
  3.     private String downloadfileUrl;  
  4.   
  5.     public String getDownloadfileUrl() {  
  6.         return downloadfileUrl;  
  7.     }  
  8.   
  9.     public void setDownloadfileUrl(String downloadfileUrl) {  
  10.         this.downloadfileUrl = downloadfileUrl;  
  11.     }  
  12.       
  13.       

猜你喜欢

转载自blog.csdn.net/laiyuan999/article/details/80285522