由于腾讯限制第三方网站直接根据封面URL引用封面图片,因此,在取到封面素材id后,需再次发送HTTPS POST请求获取图片存储在本地,显示时显示的是存储在本地的图片,在这里我要骂一句 :F*和谐C*和谐K Tencent.
然后此处给出通过HttpClient获取图片存储到本地的代码:(需先引入apache的jar包:commons-io-2.6.jar)
/**
* 以Post方式json形式的获取文件请求
* @param url
* @param parameters
* @param filePath 文件存储路径(包含文件名)
* @throws Exception
*/
public static void getFileByPost(String url,JSONObject parameters,String filePath) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setHeader("Accept","application/json");
StringEntity se = new StringEntity(parameters.toString());
se.setContentType("text/json");
httpPost.setEntity(se);
HttpResponse response=httpClient.execute(httpPost);
HttpEntity he = response.getEntity();
InputStream inputStream = he.getContent();
FileUtils.copyToFile(inputStream, new File(filePath));
}
使用示例:
public static void main(String[] args) {
String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=这里写你的ACCESSTOKEN";
JSONObject j = new JSONObject();
j.put("media_id", "这里写你获取到的图片素材的ID");
try {
getFileByPost(url, j,"D://upload/f*ckTencent.png");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}