java获取⼩程序码并转化成base64传给客户端
因为只是调api很简单,这⾥不多说直接上代码:
public ServerResponse<Object> qr_code_m_program(String scene, String path, HttpServletRequest request){
String token = Header("token");
//验证参数是否为空
List<Object> l1 = new ArrayList<Object>(){{
add(token);
}};
String CheckNull = CommonFunc.CheckNull(l1);
if (CheckNull != null) ateByErrorMessage(CheckNull);
//验证token
String uid = CommonFunc.CheckToken(request,token);
if (uid == null){
//未到
ateByErrorMessage("⾝份认证错误!");
}else {
try{
//获取accessToken
AccessToken access_token = AccessToken();
Map<String, Object> params = new HashMap<>();
params.put("scene", scene); //参数
params.put("page", path); //位置
params.put("width", 280);
params.put("is_hyaline", true);
CloseableHttpClient httpClient = ate().build();
HttpPost httpPost = new HttpPost("api.weixin.qq/wxa/getwxacodeunlimit?access_token="+AccessToken()); // 接⼝ httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSONString(params); //必须是json模式的 post
StringEntity entity;
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response = ute(httpPost);
InputStream inputStream = Entity().getContent();
// 将获取流转为base64格式
String result = "";
byte[] data = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = ad(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = ByteArray();
result = new Encoder().encode(data));
ateBySuccess("成功",result);
}catch (Exception e){
ateByErrorMessage("⾮法操作"+e.getMessage());
}
}
}
⼯具类获取AccessToken:
public static AccessToken getAccessToken() {
AccessToken token = null;
String requestUrl = "api.weixin.qq/cgi-bin/token";
String param = "grant_type=client_credential&appid="+ WxConfig.wx_app_id +"&secret="+ WxConfig.wx_app_secret;
// 发起GET请求获取凭证
JSONObject jsonObject = JSON.parseObject( UrlUtil.sendGet(requestUrl, param));
if (null != jsonObject) {
有趣的java小程序try {
token = new AccessToken();
token.String("access_token"));
token.Integer("expires_in"));
} catch (JSONException e) {
token = null;
// 获取token失败
System.out.println("获取token失败 errcode:{"+Integer("errcode")+"} errmsg:{"+String("errmsg")+"}"); // ("获取token失败 errcode:{} errmsg:{}", Integer("errcode"), String("errmsg"));
}
}
return token;
}
AccessToken类:
public class AccessToken {
//接⼝访问凭证
private String accessToken;
//接⼝有效期,单位:秒
private int expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
}
}
结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论