獲取素材,傳送圖片--微信企業開發
阿新 • • 發佈:2018-11-22
主動傳送訊息image
企業微信api
企業號開發者介面文件
企業微信介面除錯工具
微信企業號錯誤程式碼查詢工具
前言
主動傳送訊息,根據傳送訊息型別不同分為2類,一類:簡單資訊例如文字類,只需要獲取acces_token後,直接編輯文字資訊傳送給微信伺服器即可到達我們關注的微信企業號;二類:稍微複雜資訊如圖片,需要先獲取acces_token後,再發送圖片的url,型別,acces_token,獲取media_id,之後再發送給企業號;大致原理如此;整個初級專案(其中的各種id需要填入自己的,我的是測試企業號):在百度雲連線裡
直接上程式碼
程式碼中將常用操作抽離成方法,需要時直接呼叫;
一下是主題程式碼:主要是呼叫各種型別的資訊的,目前只寫了這幾個;
package com.wxwork1;
import com.wxwork.networkcode.MediaUploadUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestAccessToken3 {
/**
* 程式入口:呼叫各種方法
*/
public static void main(String[] args) {
// 傳送 GET 請求
String corpid = " " ;
String corpsecret = " ";
String access_token = WxworkUtil.GetForAT(corpid, corpsecret).get("access_token");
System.out.println("access_token:" + access_token);
// 獲取accestoken後,傳送post請求,目前傳送txt格式,傳送的引數為json格式
JSONObject jsparam = new JSONObject();
JSONObject jsparam2 = new JSONObject();
String words = "image";
if (("text").equals(words)) {//傳送文字資訊
jsparam.put("content",
"你的快遞已到,請攜帶工卡前往郵件中心領取。\n出發前可檢視<a href=\"http://work.weixin.qq.com\">郵件中心視訊實況</a>,聰明避開排隊。");
jsparam2.put("touser", "@all");
jsparam2.put("msgtype", "text");
jsparam2.put("agentid", 1000002);
jsparam2.put("text", jsparam);
jsparam2.put("safe", "0");
} else if (("textcard").equals(words)) {//傳送文字卡片資訊
jsparam.put("title", "測試通知--測試標題長度4漢字");
jsparam.put("description",
"<div class=\"gray\">2018年1月10日</div> <div class=\"normal\">恭喜你,成功測試文字卡片資訊,同時測試文字長度,1234567890</div><div class=\"highlight\">請於2018年1月11日前聯絡行政同事領取</div>");
jsparam.put("url", "https://www.zhihu.com/signup?next=%2F");
jsparam.put("btntxt", "更多的資訊和資料--測試超過4漢字");
jsparam2.put("textcard", jsparam);
jsparam2.put("msgtype", "textcard");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
} else if (("image").equals(words)) {//傳送照片資訊
String result = MediaUploadUtil.uploadMedia(access_token,"image",
"https://work.weixin.qq.com/wework_admin/frame#material/image");
System.out.println(result);
jsparam.put("media_id", WxworkUtil.readRuslt(result).get("media_id"));
jsparam2.put("image", jsparam);
jsparam2.put("msgtype", "image");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
jsparam2.put("safe", "0");
} else if (("news").equals(words)) {
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
jsonObject1.put("title", "圖文訊息測試-----字數測試");
jsonObject1.put("description", "影象訊息--詳細資訊展示或者描述");
jsonObject1.put("url", "https://www.zhihu.com/signup?next=%2F");
jsonObject1.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/imagemsg.jpeg");
jsonObject1.put("btntxt", "更多資訊");
jsonObject2.put("title", "圖文訊息測試-----字數測試");
jsonObject2.put("description", "影象訊息--詳細資訊展示或者描述");
jsonObject2.put("url", "");
jsonObject2.put("picurl","http://img15.3lian.com/2015/c1/83/d/34.jpg");
jsonObject2.put("btntxt", "更多資訊");
jsonObject3.put("title", "圖文訊息測試-----字數測試");
jsonObject3.put("description", "影象訊息--詳細資訊展示或者描述");
jsonObject3.put("url", "");
jsonObject3.put("picurl", "http://img15.3lian.com/2015/c1/83/d/30.jpg");
jsonObject3.put("btntxt", "更多資訊");
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);
jsparam2.put("news", jsonArray);
jsparam2.put("msgtype", "news");
jsparam2.put("agentid", 1000002);
jsparam2.put("touser", "@all");
}
String sendruslt = WxworkUtil.sendData(access_token, jsparam2).get("access_token");
System.out.println("post請求返回結果:" + sendruslt);
}
}
一下是自己抽離的方法(假裝是工具類):
package com.wxwork1;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wxwork.networkcode.MediaUtil;
import net.sf.json.JSONObject;
/**
* 編寫工具類:
* 1.readRuslt(String string):
* 解析微信公眾號返回資料,判斷請求成功,成功標誌:errcode:0,返回的的acces_token祕鑰,素材id,等等
* 2.GetForAT(String corpid,String corpsecret):
* 傳送get請求
* 3.sendData(String access_token,JSONObject jsparam):
* 傳送post請求
* 4.uploadMedia(String accessToken, String type, String mediaFileUrl)
* 上傳素材,mediaFileUrl是http的網址格式,本地格式為解析;
* 5.getFileEndWitsh(String contentType)
* 根據內容型別判斷副檔名
*/
public class WxworkUtil {
/**
* 編寫工具類:
* 1.readRuslt(String string):
* 解析微信公眾號返回資料,判斷請求成功,成功標誌:errcode:0,返回的的acces_token祕鑰,素材id,等等
*/
public static Map<String, String> readRuslt(String string){
Map<String, String> teMap = new HashMap<>();
String[] ss = string.substring(1, string.length()-1).split(",");
List<String> ls = Arrays.asList(ss);
System.out.println(Arrays.toString(ss));
for(String temp:ls){
teMap.put(temp.split(":")[0].replaceAll("\"",""), temp.split(":")[1].replaceAll("\"",""));
}
return teMap;
}
/*** 2.GetForAT(String corpid,String corpsecret):
* 傳送get請求
*/
public static Map<String, String> GetForAT(String corpid,String corpsecret) {
String result = null;
BufferedReader in = null;
try {
String urlNameString = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid
+ "&corpsecret=" + corpsecret;
URL realUrl = new URL(urlNameString);
System.out.println(realUrl);
// 開啟和URL之間的連線
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Content-Type", "appliction/json;charset=UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//http請求屬性
System.out.println("http請求屬性:"+connection.getRequestProperty("Content-Type"));
// 建立實際的連線
connection.connect();
// 獲取所有響應頭欄位
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭欄位
for (String key : map.keySet()) {
System.out.println("http響應標頭檔案:"+key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result=line;
}
} catch (Exception e) {
System.out.println("傳送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
//maps = readRuslt(result);
return readRuslt(result);
}
/*** 3.sendData(String access_token,JSONObject jsparam):
* 傳送post請求
*/
public static Map<String, String> sendData(String access_token,JSONObject jsparam){
String url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
PrintWriter out = null;
BufferedReader in = null;
String result = "";
System.out.println("post請求josn串:"+jsparam.toString());
try {
URL realUrl = new URL(url);
System.out.println("post請求地址:"+realUrl);
// 開啟和URL之間的連線
URLConnection conn = realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-Type", "appliction/json;charset=UTF-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 傳送POST請求必須設定如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection物件對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 傳送請求引數
out.print(jsparam);
// flush輸出流的緩衝
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("傳送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
//System.out.println(result.toString());
return readRuslt(result);
}
/**
* 上傳媒體檔案
* @param accessToken 介面訪問憑證
* @param type 媒體檔案型別,分別有圖片(image)、語音(voice)、視訊(video),普通檔案(file)
* @param media form-data中媒體檔案標識,有filename、filelength、content-type等資訊
* @param mediaFileUrl 媒體檔案的url
* 上傳的媒體檔案限制
* 圖片(image):1MB,支援JPG格式
* 語音(voice):2MB,播放長度不超過60s,支援AMR格式
* 視訊(video):10MB,支援MP4格式
* 普通檔案(file):10MB
* */
public static String uploadMedia(String accessToken, String type, String mediaFileUrl) {
String string = null;
// 拼裝請求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定義資料分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 設定請求頭Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 獲取媒體檔案上傳的輸出流(往微信伺服器寫資料)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 從請求頭中獲取內容型別
String contentType = meidaConn.getHeaderField("Content-Type");
// 根據內容型別判斷副檔名
String fileExt = MediaUtil.getFileEndWitsh(contentType);
// 請求體開始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 獲取媒體檔案的輸入流(讀取檔案)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 將媒體檔案寫到輸出流(往微信伺服器寫資料)
outputStream.write(buf, 0, size);
}
// 請求體結束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 獲取媒體檔案上傳的輸入流(從微信伺服器讀資料)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回結果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
string = jsonObject.toString();
} catch (Exception e) {
String error = String.format("上傳媒體檔案失敗:%s", e);
System.out.println(error);
}
return string;
}
/**
* 根據內容型別判斷副檔名
*
* @param contentType 內容型別
* @return
*/
public static String getFileEndWitsh(String contentType) {
String fileEndWitsh = "";
if ("image/jpeg".equals(contentType))
fileEndWitsh = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileEndWitsh = ".mp3";
else if ("audio/amr".equals(contentType))
fileEndWitsh = ".amr";
else if ("video/mp4".equals(contentType))
fileEndWitsh = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileEndWitsh = ".mp4";
return fileEndWitsh;
}
}
不知道是那抄的工具類:
package com.wxwork.networkcode;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
/**
* Description:
* Author:py
*/
public class MediaUploadUtil {
/**
* 上傳媒體檔案
* @param accessToken 介面訪問憑證
* @param type 媒體檔案型別,分別有圖片(image)、語音(voice)、視訊(video),普通檔案(file)
* @param media form-data中媒體檔案標識,有filename、filelength、content-type等資訊
* @param mediaFileUrl 媒體檔案的url
* 上傳的媒體檔案限制
* 圖片(image):1MB,支援JPG格式
* 語音(voice):2MB,播放長度不超過60s,支援AMR格式
* 視訊(video):10MB,支援MP4格式
* 普通檔案(file):10MB
* */
public static String uploadMedia(String accessToken, String type, String mediaFileUrl) {
String string = null;
// 拼裝請求地址
String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定義資料分隔符
String boundary = "------------7da2e536604c8";
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 設定請求頭Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 獲取媒體檔案上傳的輸出流(往微信伺服器寫資料)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 從請求頭中獲取內容型別
String contentType = meidaConn.getHeaderField("Content-Type");
// 根據內容型別判斷副檔名
String fileExt = MediaUtil.getFileEndWitsh(contentType);
// 請求體開始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 獲取媒體檔案的輸入流(讀取檔案)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 將媒體檔案寫到輸出流(往微信伺服器寫資料)
outputStream.write(buf, 0, size);
}
// 請求體結束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();
// 獲取媒體檔案上傳的輸入流(從微信伺服器讀資料)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
// 使用JSON-lib解析返回結果
JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
string = jsonObject.toString();
} catch (Exception e) {
String error = String.format("上傳媒體檔案失敗:%s", e);
System.out.println(error);
}
return string;
}
}
還有些,太多了,在百度雲連線裡