前言
搞了大半天,不论是okhttp还是自己写httpClient都试过了,依旧不行,最后在网上找到一个仁兄的代码,改了改,终于可以了!!!!!
在线求解,为什么okhttp和httpClient不行?测试了其他post请求都是正常的,就只有微信不行。
微信的接口太太太太恶心了!!!
代码
这是修改后的代码,测试完全可以,具体是哪个仁兄哪找到来改的记不住了,如果你看到了,可以给我留言或私信,我加连接;感谢🙏
这里生成的base64的图片,文件流保留了,如果需要存图片的可以放开注释,自己改一改
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author N_Xiang
* @describe 微信太阳码生成
* @time 2021/7/4 10:54 下午
*/
public class xdemo {
public static String getminiqrQr(String accessToken,String code) {
RestTemplate rest = new RestTemplate();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
Map<String,Object> param = new HashMap<>();
param.put("page", "pages/index/index");
param.put("scene", "code="+code);
param.put("width", 430);
param.put("auto_color", false);
Map<String,Object> line_color = new HashMap<>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
byte[] result = entity.getBody();
if (result.length<1000){
return StringToHex.hexStringToString(StringToHex.bytesToHexString(result));
}
BASE64Encoder encoder = new BASE64Encoder();
// inputStream = new ByteArrayInputStream(result);
return "data:image/png;base64,"+encoder.encode(result);
// File file = new File("C:/Users/wangqiulin/Desktop/1.png");
// if (!file.exists()){
// file.createNewFile();
// }
// outputStream = new FileOutputStream(file);
// int len = 0;
// byte[] buf = new byte[1024];
// while ((len = inputStream.read(buf, 0, 1024)) != -1) {
// outputStream.write(buf, 0, len);
// }
// outputStream.flush();
} catch (Exception e) {
log.debug("调用小程序生成微信永久小程序码URL接口异常");
} finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}