代码如下,我保存的图片是40大小,但是打开是破损的,显然是保存失败了,我看了下官方接口直接访问是404,其他授权啊什么的,访问都是返回错误代码,是不是这接口其实还没开放啊
获取token和执行封装的生成小程序码的代码
String access_token = getAccessToken();
String tourl = "pages/products/products?id=" + pid;
String ur = GetTTPostUrl(access_token, Tool.getURLEncodeString(tourl,"utf-8"), "product-" + pid,
request);
product.setQrcode(ur);
productDao.update(product);
//头条小程序二维码
public static String GetTTPostUrl(String access_token,String tourl,String picname,HttpServletRequest request) throws Exception {
String url ="https://developer.toutiao.com/api/apps/qrcode?access_token=";
Map<String, Object> map = new HashMap<String, Object>();
map.put("path", tourl);//你二维码中跳向的地址
map.put("width", "430");//图片大小
JSONObject json = JSONObject.fromObject(map);
return httpPostWithJSON(url + access_token, json.toString(),picname,request);
}
/**
* 设置图片保存路径
* @param url
* @param json
* @param id
* @param request
* @return
* @throws Exception
*/
public static String httpPostWithJSON(String url, String json,String picname,HttpServletRequest request)
throws Exception {
String pic = "";
HttpClient httpClient=HttpClients.createDefault();
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);
HttpResponse response = httpClient.execute(httpPost);
String path = request.getSession().getServletContext().getRealPath("/QRcode");//保存的服务器地址
String uploadSysUrl=null;
System.out.println(response.toString());
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
InputStream instreams = resEntity.getContent();
uploadSysUrl = path+"/";
File saveFile = new File(uploadSysUrl+picname+".jpg");
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
saveToImgByInputStream(instreams, uploadSysUrl, picname+".jpg");
pic="https://"+GetWX.getPro("yuming")+"/QRcode/"+picname+".jpg";
}
}
httpPost.abort();
return pic;
//return "http://127.0.0.1/upload/"+id+".jpg";
}
/**
* @param instreams 二进制流
* @param imgPath 图片的保存路径
* @param imgName 图片的名称
* @return
*/
public static void saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
if(instreams != null) {
try {
File file = new File(imgPath + imgName);//可以是任何图片格式.jpg,.png等
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
int allsize=0;//流的总大小
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
allsize+=nRead;
}
System.out.println(imgPath+imgName+"大小:"+allsize);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
instreams.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}