小程序生成二维码(带参数)


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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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;

import net.sf.json.JSONObject;

public class HttpClientConnectionManager {
	/**
	 * @param reqUrl
	 *            基础的url地址
	 * @param params
	 *            查询参数
	 * @return 构建好的url
	 */

	public static String httpPostWithJSON(HttpServletRequest request, 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" + "/";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String dateStr = sdf.format(new Date());
				String xdPath = "/upload/" + dateStr;
				String filePath = request.getServletContext().getRealPath(xdPath);// 保存文件路径
				File saveFile = new File(filePath);
				// 判断这个文件(saveFile)是否存在
				if (!saveFile.exists()) {
					// 如果不存在就创建这个文件夹
					saveFile.mkdirs();
				}
				String newHeadImgName = "";// 重新设置要保存头像的文件名
				// 获取当前时间
				Date d = new Date();
				newHeadImgName += "" + d.getTime() + ((int) (Math.random() * 9000 + 1000)) + ".jpg";
				saveToImgByInputStream(instreams, filePath, newHeadImgName);
				result = xdPath + "/" + newHeadImgName;
			}
		}
		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 request
	 * @param access_token
	 * @param path
	 * @param width
	 * @param scene
	 * @return
	 */
	public static String createwxaqrcode(HttpServletRequest request, String access_token, String path, String width,
			String scene) {
		String URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
		// 二维码图片位置
		String downloadUrl = null;
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, String> line_color = new HashMap<String, String>();
			line_color.put("r", "0");
			line_color.put("g", "0");
			line_color.put("b", "0");
			map.put("path", path);
			map.put("width", width);
			map.put("scene", scene);
			map.put("auto_color", false);
			map.put("line_color", line_color);
			JSONObject json = JSONObject.fromObject(map);
			downloadUrl = HttpClientConnectionManager.httpPostWithJSON(request, URL, json.toString(), scene);
			// 返回给前端的后台服务器文件下载路径

		} catch (Exception e) {
			e.printStackTrace();
		}
		return downloadUrl;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中生成参数小程序二维码,可以使用第三方库或者API来实现。以下是一种可能的方法: 首先,你需要选择一个适合的二维码生成库。在这里,我们以Zxing库为例进行说明。你可以在Maven中添加对Zxing库的依赖,然后在Java项目中使用它。 接下来,你需要创建一个字符串,以包含参数小程序链接。例如,你可以将参数附加到小程序链接的末尾,如下所示:https://xxx.xxx.xxx?param1=xxx&param2=xxx。请根据你的具体需求自行替换链接和参数。 然后,你可以使用Zxing库生成参数小程序二维码。以下是一个代码示例: ```java import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class QrCodeGenerator { public static void main(String[] args) { String content = "https://xxx.xxx.xxx?param1=xxx&param2=xxx"; // 替换为你的参数小程序链接 int width = 300; int height = 300; try { BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height); BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { qrCodeImage.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB()); } } File outputFile = new File("qr_code.jpg"); // 保存二维码的文件名和路径 ImageIO.write(qrCodeImage, "jpg", outputFile); } catch (WriterException | IOException e) { e.printStackTrace(); } } } ``` 运行上述代码后,它将生成一个名为"qr_code.jpg"的图像文件,其中包含参数小程序二维码。 当然,以上只是一种实现方法,你也可以使用其他类库或API来生成参数小程序二维码。希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值