java微信小程式 獲取二維碼
阿新 • • 發佈:2019-01-02
如果用Spring那套RestTemplate不能獲取,或者獲取了生成的圖片檔案是無法開啟的,大小是150多k的(當寬度為430的時候,應該是55k左右),可以看看我的方法
package com.wx.scooter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http .client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders ;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wx.scooter.tool.CheckTool ;
import com.wx.scooter.tool.Constant;
public class TestQR {
public static void main2(String[] args) throws Exception {
//獲取token
String result1 = get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constant.NATIVE_APP_ID+"&secret="+Constant.NATIVE_APP_SECRET);
String access_token = JSONObject.parseObject(result1).getString("access_token");
if(CheckTool.isString(access_token)) {
System.out.println("token為");
System.out.println(access_token);
Map<String, Object> params = new HashMap<>();
params.put("scene", "test");
params.put("page", "pages/index/index");
params.put("width", 430);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);
StringEntity entity;
entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
File targetFile = new File("D:\\");
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream("D:\\upload\\5.png");
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
} else {
System.out.println("獲取access_token錯誤");
}
}
/**
* 傳送get請求
* @param url
* @return
*/
public static String get(String url) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<String> entity = new HttpEntity<String>(url, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return responseEntity.getBody();
}
}