微信公衆平台
這兩天在網上看了其他的方法,也調試了一些,然後自己整理了一下,友善自己學習,也友善大家使用。
調用接口
1、java調用上傳圖檔接口
public final static String IMAGE = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";public staticString uploadimg(MultipartFile file ) {
CloseableHttpClient client=HttpClients.createDefault();//建立httppost
String requestUrl = IMAGE.replace("ACCESS_TOKEN", access_token);//替換調access_token
HttpPost post = newHttpPost(requestUrl);
RequestConfig config= RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build();
post.setConfig(config);
File f= null;try{
f= newFile(file.getOriginalFilename());
inputStreamToFile(file.getInputStream(),f);
FileUtils.copyInputStreamToFile(file.getInputStream(), f);
}catch(IOException e) {
e.printStackTrace();
}
String name=f.getName();
FileBody fileBody= newFileBody(f, ContentType.DEFAULT_BINARY,name);
String filename=fileBody.getFilename();long contentLength =fileBody.getContentLength();
ContentType contentType=fileBody.getContentType();
MultipartEntityBuilder builder=MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("media", fileBody);//相當于 ,比對@RequestParam("file")//.addPart()可以設定模拟浏覽器的表單送出
HttpEntity entity =builder.build();
post.setEntity(entity);
String result= "";try{
CloseableHttpResponse e=client.execute(post);
HttpEntity resEntity=e.getEntity();if(entity != null) {
result=EntityUtils.toString(resEntity);
System.out.println("response content:" +result);
}
}catch(IOException var10) {
System.out.println("請求解析驗證碼io異常 "+var10);//logger.error("請求解析驗證碼io異常",var10);
var10.printStackTrace();
}returnresult;
}public static voidinputStreamToFile(InputStream ins, File file) {try{
OutputStream os= newFileOutputStream(file);int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer,0, bytesRead);
}
os.close();
ins.close();
}catch(Exception e) {
e.printStackTrace();
}
}
2、新增永久圖檔素材
隻需要修改 requestUrl
public final static String ADD_MATERIAL_IMAGE = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
3、新增永久視訊素材
public final static String ADD_MATERIAL_IMAGE = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
public staticString uploadPermanentMaterial(File file, String type, String title, String introduction) {
String url= ADD_MATERIAL_IMAGE.replace("ACCESS_TOKEN", access_token).replace("TYPE", type);//替換調access_token
String result = null;try{
URL uploadURL= newURL(url);
HttpURLConnection conn=(HttpURLConnection) uploadURL.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary= "-----------------------------" +System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +boundary);
OutputStream output=conn.getOutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());byte[] data = new byte[1024];int len = 0;
FileInputStream input= newFileInputStream(file);while ((len = input.read(data)) > -1) {
output.write(data,0, len);
}
if ("video".equals(type)) {
output.write(("--" + boundary + "\r\n").getBytes());
output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
}
output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
output.flush();
output.close();
input.close();
InputStream resp=conn.getInputStream();
StringBuffer sb= newStringBuffer();while ((len = resp.read(data)) > -1)
sb.append(new String(data, 0, len, "utf-8"));
resp.close();
result=sb.toString();
}catch(IOException e) {//....
}returnresult;
}
上傳視訊的這個方法也可以上傳其他素材。
4、上傳永久圖文素材
首先考慮傳值,官方的示例
{"articles": [{"title": TITLE,"thumb_media_id": THUMB_MEDIA_ID,"author": AUTHOR,"digest": DIGEST,"show_cover_pic": SHOW_COVER_PIC(0 / 1),"content": CONTENT,"content_source_url": CONTENT_SOURCE_URL,"need_open_comment":1,"only_fans_can_comment":1},//若新增的是多圖文素材,則此處應還有幾段articles結構
]
}
1、直接put json,下面是一個簡單的例子。這樣很容易完成示例
//{ "tag":{ "id":134,//标簽id "name":"廣東" } }
JSONObject json1= newJSONObject();
json1.put("name", "廣東");
JSONObject json= newJSONObject();
json.put("tag", json1);
2、使用實體類,可以參數與json轉換
public classAddNewsParam {privateArticles [] articles;public classArticles {private String title;//圖文消息的标題
private String thumb_media_id;//圖文消息的封面圖檔素材id(必須是永久mediaID)
private String author;//作者
private String digest;//圖文消息的摘要,僅有單圖文消息才有摘要,多圖文此處為空
private Integer show_cover_pic;//是否顯示封面,0為false,即不顯示,1為true,即顯示
private String content;//圖文消息的具體内容,支援HTML标簽,必須少于2萬字元,小于1M,且此處會去除JS