java 微信开发图片发送,微信开发?Java上传Base64图片

该博客展示了如何使用Java的Apache HttpClient库将Base64编码的图片上传到微信的卡券接口。首先,通过Apache Commons Codec解码Base64字符串到临时文件,然后利用HttpClient创建POST请求,将文件作为MultipartEntity发送到微信API。
摘要由CSDN通过智能技术生成

class="java">import org.apache.commons.codec.binary.Base64;

import org.apache.log4j.LogManager;

import org.apache.log4j.Logger;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

/**

* 文件处理工具类

*/

public class FileHelpers {

private static final Logger logger = LogManager.getLogger(FileHelpers.class);

/**

* 解析base64格式图片,并保存到临时目录

*

* @param base64Str base64格式图片

* @param file 临时文件对象

* @return File Object

* @throws Exception

*/

public static void decodeBase64ToFile(File file,String base64Str) throws Exception {

OutputStream out = null;

try {

int prefixIndex = base64Str.indexOf(",");

byte[] buffer = Base64.decodeBase64(base64Str.substring(prefixIndex + 1));

out = new FileOutputStream(file);

out.write(buffer);

out.flush();

} catch (Exception e) {

logger.debug("decodeBase64ToFile raise exception:" + e.getMessage());

throw new Exception(e.getMessage());

} finally {

if (out!=null) {

out.close();

}

}

}

}

/*********************************************/

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.HttpClientUtils;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import java.io.File;

import java.util.Map;

public class WeixinMediaUtils {

private final Logger logger = LogManager.getLogger(ServiceWeixinMedias.class);

/**

* 卡券 上传图片接口

*

* @param accessToken 开放平台/或者公众平台的accessToken

* @param imgStream 图片base64字符串

* @return 上传成功后,返回的图片Url

*/

public static Map uploadimg(String accessToken, String imgStream) {

File tempFile = null;

CloseableHttpClient httpClient = null;

CloseableHttpResponse response = null;

try {

String url = String.format("%s%s",

"https://api.weixin.qq.com/cgi-bin/media/uploadimg",

"ACCESS_TOKEN="+accessToken))

);

tempFile = File.createTempFile("weixin_media", ".jpg");

FileHelpers.decodeBase64ToFile(tempFile, imgStream);

HttpPost httpPost = new HttpPost(url);

FileBody fileBody = new FileBody(tempFile);

HttpEntity httpEntity = MultipartEntityBuilder.create().addPart("buffer", fileBody).build();

httpPost.setEntity(httpEntity);

httpClient = HttpClients.createDefault();

response = httpClient.execute(httpPost);

HttpEntity responseEntity = response.getEntity();

if (responseEntity != null) {

String responseEntityStr = EntityUtils.toString(response.getEntity());

System.out.println(responseEntityStr);

System.out.println("Response content length: " + responseEntity.getContentLength());

return JsonHelpers.deserializeToMap(responseEntityStr).orElseThrow(() -> new Exception("uploadimg failed,response realizeToMap raise Exception"));

} else {

throw new Exception(String.format("call weixin interface fail,file 【%s】 upload fail", tempFile.getAbsolutePath()));

}

} catch (Throwable t) {

t.printStackTrace();

throw new Exception(t.getMessage());

} finally {

if (tempFile!=null) {

tempFile.delete();

}

if (httpClient!=null) {

HttpClientUtils.closeQuietly(httpClient);

}

if (response!=null) {

HttpClientUtils.closeQuietly(response);

}

}

}

? ? Java使用HttpClient,将Base64图片上传到微信!!

? ? 诸多不完善之处,敬请指正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java生成微信小程序带参数二维码的完整代码: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.json.JSONObject; public class WxMaQrcodeUtils { private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode"; private static final String PARAM_PAGE = "page"; private static final String PARAM_SCENE = "scene"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; /** * 获取access_token * * @param appid 小程序appid * @param secret 小程序secret * @return access_token */ public static String getAccessToken(String appid, String secret) { String accessToken = null; try { String url = ACCESS_TOKEN_URL + "?grant_type=client_credential&appid=" + appid + "&secret=" + secret; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = con.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } bufferedReader.close(); JSONObject jsonObject = new JSONObject(stringBuilder.toString()); accessToken = jsonObject.getString("access_token"); } } catch (Exception e) { e.printStackTrace(); } return accessToken; } /** * 生成小程序带参数二维码 * * @param accessToken 小程序access_token * @param page 小程序页面路径 * @param scene 小程序页面参数 * @return base64格式的二维码图片数据 */ public static String createQrcode(String accessToken, String page, String scene) { String base64Image = null; try { Map<String, Object> params = new HashMap<>(); params.put(PARAM_PAGE, page); params.put(PARAM_SCENE, scene); URL obj = new URL(API_URL + "?access_token=" + accessToken); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); con.getOutputStream().write(new JSONObject(params).toString().getBytes("UTF-8")); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = con.getInputStream(); byte[] imageBytes = new byte[inputStream.available()]; inputStream.read(imageBytes); inputStream.close(); base64Image = Base64.encodeBase64String(imageBytes); } } catch (Exception e) { e.printStackTrace(); } return base64Image; } public static void main(String[] args) { String appid = "your_appid"; String secret = "your_secret"; String accessToken = getAccessToken(appid, secret); String page = "pages/index/index"; String scene = "key=value"; String base64Image = createQrcode(accessToken, page, URLEncoder.encode(scene)); System.out.println(base64Image); } } ``` 注意,需要引入Apache Commons Codec库。 其中,getAccessToken方法用于获取小程序的access_token,createQrcode方法用于生成小程序带参数二维码并返回base64格式的图片数据。在main方法中调用以上两个方法即可生成小程序二维码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值