java調用企業微信接口發送文件功能



結合幾位大佬的代碼后實現此功能:感謝大佬讓我完成此功能的實現,如有侵權,立刻刪除。
借鑒文章地址:
java調用企業微信接口發送消息https://blog.csdn.net/zxl782340680/article/details/79876502。介紹的十分詳細,相當感動,圖片加代碼。(這個是發送普通文本消息的)一下子代碼就通過了。
corpID之類的頁面參數告訴在哪里獲取,支持下作者。
微信小程序客服消息新增臨時素材接口java實現https://www.cnblogs.com/wbxk/p/8581195.html
 代碼

一、實體類:
注意:json字符串和實體類是對應的:一定要對應,我就是沒有對應導致浪費一天半時間在修改40007錯誤。最后發現我輸出出來的json和官方文檔的不一樣。這個是我踩的最大的坑media_id明明獲取到了,確報40007media_id不合法,讓我一直以為是我id獲取錯了,換了接口等,怎么都不好使。最后發現官方文檔請求數據是這樣的

 


我的是:
“media_id”:“獲取到的media_id”沒有前面的file。
相差這么大我竟然沒發現,最后還是我公司哥給我發現的。希望自己以后認真一點吧。

 

/**
* 微信消息發送實體類
* @author
*/
public class WeChatData {
//發送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
/**
* 成員賬號
*/
private String touser;
/**
* 消息類型
*/
private String msgtype;
/**
* 企業應用的agentID
*/
private int agentid;
/**
* 實際接收Map類型數據
*/

private Object file;

public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public int getAgentid() {
return agentid;
}
public void setAgentid(int agentid) {
this.agentid = agentid;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}

public Object getFile() {
return file;
}

public void setFile(Object file) {
this.file = file;
}
}

 

二、微信授權請求

public class WeChatUrlData {
/**
* 企業Id
*/
private String corpid;
/**
* secret管理組的憑證密鑰
*/
private String corpsecret;
/**
* 獲取ToKen的請求
*/
private String Get_Token_Url;
/**
* 發送消息的請求
*/
private String SendMessage_Url;
public String getCorpid() {
return corpid;
}
public void setCorpid(String corpid) {
this.corpid = corpid;
}
public String getCorpsecret() {
return corpsecret;
}
public void setCorpsecret(String corpsecret) {
this.corpsecret = corpsecret;
}
public void setGet_Token_Url(String corpid,String corpsecret) {
this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
}
public String getGet_Token_Url() {
return Get_Token_Url;
}
public String getSendMessage_Url(){
SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
return SendMessage_Url;
}
}

 


三、微信發送消息

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class WeChatMsgSend {
private CloseableHttpClient httpClient;
/**
* 用於提交登陸數據
*/
private HttpPost httpPost;
/**
* 用於獲得登錄后的頁面
*/
private HttpGet httpGet;


public static final String CONTENT_TYPE = "Content-Type";


SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


private static Gson gson = new Gson();


/**
* 微信授權請求,GET類型,獲取授權響應,用於其他方法截取token
* @param Get_Token_Url
* @return String 授權響應內容
* @throws IOException
*/
protected String toAuth(String Get_Token_Url) throws IOException {


httpClient = HttpClients.createDefault();
httpGet = new HttpGet(Get_Token_Url);
CloseableHttpResponse response = httpClient.execute(httpGet);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
} finally {
response.close();
}
LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
return resp;
}


/**corpid應用組織編號 corpsecret應用秘鑰
* 獲取toAuth(String Get_Token_Url)返回結果中鍵值對中access_token鍵的值
* @param
*/
public String getToken(String corpid,String corpsecret) throws IOException {
WeChatMsgSend sw = new WeChatMsgSend();
WeChatUrlData uData = new WeChatUrlData();
uData.setGet_Token_Url(corpid,corpsecret);
String resp = sw.toAuth(uData.getGet_Token_Url());
System.out.println("resp=====:"+resp);
try{
Map<String, Object> map = gson.fromJson(resp,new TypeToken<Map<String, Object>>() {}.getType());
return map.get("access_token").toString();
}catch (Exception e) {
return resp;
}
}

/**
* @Title:創建微信發送請求post數據
* touser發送消息接收者 ,msgtype消息類型(文本/圖片等),
* application_id應用編號。
* media_id文件id,可以調用上傳臨時素材接口獲取
* 本方法適用於text型微信消息,contentKey和contentValue只能組一對
* @return String
*/
public String createpostdata(String touser, String msgtype,
int application_id,String file,Object media_id) {
WeChatData wcd = new WeChatData();
wcd.setTouser(touser);
wcd.setAgentid(application_id);
wcd.setMsgtype(msgtype);
Map<Object, Object> content = new HashMap<Object, Object>();
content.put(file,media_id);
wcd.setFile(content);

return gson.toJson(wcd);
}


/**
* @Title 創建微信發送請求post實體
* charset消息編碼 ,contentType消息體內容類型,
* url微信消息發送請求地址,data為post數據,token鑒權token
* @return String
*/
public String post(String charset, String contentType, String url,
String data,String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url+token);
httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, charset));
CloseableHttpResponse response = httpclient.execute(httpPost);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
} finally {
response.close();
}
LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
return resp;
}
}

 

四、上傳臨時文件獲取media_id

public class UploadMeida {
/**
* 新增臨時素材
*
* @param fileType
* @param filePath
* @return
* @throws Exception
*/
public JSONObject UploadMeida(String fileType, String filePath) throws Exception {
// 返回結果
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {

throw new IOException("文件不存在");
}
WeChatMsgSend swx = new WeChatMsgSend();
String token = swx.getToken("ww6f36fa1463b963b0",
"1PF1i9ypGkMakBd-8nKw9kUeZkc95opSkm8MJGChSMw");
if (token == null) {
throw new IOException("未獲取到token");
}
String uploadTempMaterial_url="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
uploadTempMaterial_url = uploadTempMaterial_url.replace("ACCESS_TOKEN", token).replace("TYPE", fileType);
URL url = new URL(uploadTempMaterial_url);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 以POST方式提交表單
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);// POST方式不能使用緩存
// 設置請求頭信息
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 設置邊界
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 請求正文信息
// 第一部分
StringBuilder sb = new StringBuilder();
sb.append("--");// 必須多兩條道
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");


// 獲得輸出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 輸出表頭
out.write(sb.toString().getBytes("UTF-8"));
// 文件正文部分
// 把文件以流的方式 推送道URL中
DataInputStream din = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = din.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
din.close();
// 結尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");// 定義數據最后分割線
out.write(foot);
out.flush();
out.close();
if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {

StringBuffer strbuffer = null;
BufferedReader reader = null;
try {
strbuffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineString = null;
while ((lineString = reader.readLine()) != null) {
strbuffer.append(lineString);

}
if (result == null) {
result = strbuffer.toString();

}
} catch (IOException e) {

e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}

}
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject;

}
}

 

 


五、測試類

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

public class Test {
public static void main(String[] args) {
UploadMeida uploadMeida = new UploadMeida();
String fileType = "file";
String filePath = "src/main/resources/excel/工資條.xls";
WeChatMsgSend swx = new WeChatMsgSend();
try {
String token = swx.getToken("你的corpID",
"你的Secret");
JSONObject jsonObject = uploadMeida.UploadMeida(fileType, filePath);
Object media_id = jsonObject.get("media_id");


String postdata = swx.createpostdata(
"你要發送的賬戶名", "file", 1000002, "media_id", media_id);
String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, token);
System.out.println("獲取到的toke n======>" + token);
System.out.println("請求數據======>" + postdata);
System.out.println("發送微信的響應數據======>" + resp);
System.err.println(media_id);

} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM