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

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

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

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

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

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

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

如果图片有文件

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

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


HttpClientConnectionManager 自定义工具类

 package cn.edu.hbcf.plugin.wx.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
 
public class HttpClientConnectionManager {
    /**
     * @param reqUrl
     *            基础的url地址
     * @param params
     *            查询参数
     * @return 构建好的url
     */
         
     
    public static String httpPostWithJSON(String url, String json,String id)
            throws Exception {
        String result = null;
        // 将JSON进行UTF-8编码,以便传输中文
        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8); 
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");  
        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
        httpPost.setEntity(se);
        // httpClient.execute(httpPost);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                InputStream instreams = resEntity.getContent(); 
               // ResourceBundle systemConfig = ResourceBundle.getBundle("config/system", Locale.getDefault());
              //  String uploadSysUrl = systemConfig.getString("agentImgUrl")+id+"/";
              //  File saveFile = new File(uploadSysUrl+id+".jpg");
                String uploadSysUrl = "D:\\upload"+"/";
                File saveFile = new File(uploadSysUrl+id+".jpg");
                   // 判断这个文件(saveFile)是否存在
                   if (!saveFile.getParentFile().exists()) {
                       // 如果不存在就创建这个文件夹
                       saveFile.getParentFile().mkdirs();
                   }
                saveToImgByInputStream(instreams, uploadSysUrl, id+".jpg");
            }
        }
        return result;
    } 
     
    /* @param instreams 二进制流
    * @param imgPath 图片的保存路径
    * @param imgName 图片的名称
    * @return
    *      1:保存正常
    *      0:保存失败
    */
   public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName) throws FileNotFoundException{
  
       int stateInt = 1;
       File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
       FileOutputStream fos=new FileOutputStream(file);
       if(instreams != null){
           try {
                                 
               byte[] b = new byte[1024];
               int nRead = 0;
               while ((nRead = instreams.read(b)) != -1) {
                   fos.write(b, 0, nRead);
               }
                              
           } catch (Exception e) {
               stateInt = 0;
               e.printStackTrace();
           } finally {
        	   
               try {
            	   fos.flush();
				   fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			} 
           }
       }
       return stateInt;
   }      
   public static boolean exists(String imgPath){
       File saveFile = new File(imgPath);
       if (!saveFile.getParentFile().exists()) {
           return false;
       }else{
           //如果存在判断这个文件的大小
           if(saveFile.length()>0){
               System.out.println("--------------------------------"+saveFile.length());
               return true;
           }else{
               return false;
           }
       }
     
   }      
   /**
    * 向指定URL发送GET方法的请求
    * 
    * @param url
    *            发送请求的URL
    * @param param
    *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
    * @return URL 所代表远程资源的响应结果
    */
   public static String sendGet(String url, String param) {
       String result = "";
       BufferedReader in = null;
       try {
           String urlNameString = url + "?" + param;
           System.out.println(urlNameString+"........");
           URL realUrl = new URL(urlNameString);
           // 打开和URL之间的连接
           URLConnection connection = realUrl.openConnection();
           // 设置通用的请求属性
           connection.setRequestProperty("accept", "*/*");
           connection.setRequestProperty("connection", "Keep-Alive");
           connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           // 建立实际的连接
           connection.connect();
           // 获取所有响应头字段
           Map<String, List<String>> map = connection.getHeaderFields();
           // 遍历所有的响应头字段
           for (String key : map.keySet()) {
               System.out.println(key + "--->" + map.get(key));
           }
           // 定义 BufferedReader输入流来读取URL的响应
           in = new BufferedReader(new InputStreamReader(
                   connection.getInputStream()));
           String line;
           while ((line = in.readLine()) != null) {
               result += line;
           }
       } catch (Exception e) {
           System.out.println("发送GET请求出现异常!" + e);
           e.printStackTrace();
       }
       // 使用finally块来关闭输入流
       finally {
           try {
               if (in != null) {
                   in.close();
               }
           } catch (Exception e2) {
               e2.printStackTrace();
           }
       }
       return result;
   }
 
   
   
   public static Object httpPostWithJSON2(String url, String json,String id)
           throws Exception {
       // 将JSON进行UTF-8编码,以便传输中文
	   InputStream instreams = null;
       String encoderJson = URLEncoder.encode(json, HTTP.UTF_8); 
       DefaultHttpClient httpClient = new DefaultHttpClient();
       HttpPost httpPost = new HttpPost(url);
       httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");  
       StringEntity se = new StringEntity(json);
       se.setContentType("application/json");
       se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
       httpPost.setEntity(se);
       // httpClient.execute(httpPost);
       HttpResponse response = httpClient.execute(httpPost);
       if (response != null) {
           HttpEntity resEntity = response.getEntity();
           if (resEntity != null) {
                instreams = resEntity.getContent(); 
             
           }
       }
       return instreams;
   }
    
}

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

/**
	 *  获取微信二维码
	 * @param path
	 * @param width 二维码的宽度
	 * @param access_token 
	 * @return
	 */
	@RequestMapping(value = "/createwxaqrcode")
	@ResponseBody
	public Object  createwxaqrcode(String access_token,String path,String width, String id ){
		AgentDTO agentDTO = new AgentDTO();
		String URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode";  
		//二维码图片位置
		String agentImgDownloadUrl = "D:\\upload";
        try {  
        	AgentReqView agentResView = new AgentReqView();
        	Map<String, Object> map = new HashMap<String, Object>();
    	    map.put("path", path);
    	    map.put("width", width);
            JSONObject json = JSONObject.fromObject(map);
            HttpClientConnectionManager.httpPostWithJSON(URL+"?access_token="+ access_token, json.toString(),id );
            String downloadUrl = agentImgDownloadUrl+ id+  "/";
            //返回给前端的后台服务器文件下载路径
            String downloadfileUrl = downloadUrl + id + ".jpg";
            agentResView.setDownloadfileUrl(downloadfileUrl);
            agentDTO.setResultCode("200");
            agentDTO.setDesc("成功");
            agentDTO.setBody(agentResView);
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return agentDTO;
	}

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

import java.util.List;

public class AgentDTO {
	private String resultCode;
	private String desc;
	private AgentReqView body;
	
	public AgentDTO (){
		
	}
	
	public AgentDTO (String resultCode,String desc){
		this.setResultCode(resultCode);
		this.setDesc(desc);
		
	}
	public String getResultCode() {
		return resultCode;
	}
	public void setResultCode(String resultCode) {
		this.resultCode = resultCode;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}

	public AgentReqView getBody() {
		return body;
	}

	public void setBody(AgentReqView body) {
		this.body = body;
	}
	

	
}

public class AgentReqView {

	private String downloadfileUrl;

	public String getDownloadfileUrl() {
		return downloadfileUrl;
	}

	public void setDownloadfileUrl(String downloadfileUrl) {
		this.downloadfileUrl = downloadfileUrl;
	}
	
	
}




  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在微信小程序获取二维码,可以使用微信提供的API。通过调用获取小程序二维码的API,你可以生成一张小程序的二维码图片。 你可以参考微信官方文档中的相关内容,其中包括获取二维码的详细说明和示例代码。 除了普通二维码外,你还可以下载不同尺寸的普通二维码或小程序二维码。通过点击下载按钮,你可以获取不同尺寸的二维码图片。 需要注意的是,通过该接口生成的小程序二维码是永久有效的。但是,生成二维码的数量是有限制的,请谨慎使用。并且,用户扫描该码后将直接进入对应页面。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [微信小程序学习之路——API获取二维码](https://blog.csdn.net/CSDN_XUWENHAO/article/details/89165601)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [生成微信小程序发布上线后的二维码获取微信小程序二维码微信小程序二维码如何生成?](https://blog.csdn.net/Shimeng_1989/article/details/126405337)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值