import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import com.alibaba.fastjson.JSONObject;
import com.cetcnav.operations.util.WeixinUtil;
public class Main {
public static void main(String[] args) {
try {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx30d92d5c1507e2c6&secret=9fbaee41a1e2db00214321e28b9fda68";
JSONObject data = WeixinUtil.httpRequest(url, "GET", null);
String token = data.getString("access_token");
String createurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
String json = "{\"button\":[{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"智慧接待\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx30d92d5c1507e2c6&redirect_uri=http%3A%2F%2F222.222.216.214%3A9900%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FsmartReceptionHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"}]}]}";
JSONObject JSONObject = WeixinUtil.httpRequest(createurl, "POST", json);
System.out.println(JSONObject.toString());
String URL = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" + token;
JSONObject josn = WeixinUtil.httpRequest(URL, "GET", null);
System.out.println(josn);
} catch (Exception e) {
System.out.println("---");
}
}
public static JSONObject addMaterialEver(String fileurl, String type, String token) {
try {
File file = new File(fileurl);
String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type="
+ type;
String result = connectHttpsByPost(path, null, file);
result = result.replaceAll("[\\\\]", "");
System.out.println("result:" + result);
JSONObject resultJSON = JSONObject.parseObject(result);
if (resultJSON != null) {
if (resultJSON.get("media_id") != null) {
System.out.println("上传" + type + "永久素材成功");
return resultJSON;
} else {
System.out.println("上传" + type + "永久素材失败");
}
}
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
public static String connectHttpsByPost(String path, String KK, File file)
throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
URL urlObj = new URL(path);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
String result = null;
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.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\";filelength=\"" + file.length() + "\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
return result;
}
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSONObject;
import com.cetcnav.operations.weixin.entity.Image;
import com.cetcnav.operations.weixin.entity.ImageMessage;
import com.cetcnav.operations.weixin.entity.TextMessage;
import com.google.inject.spi.Element;
import com.sun.xml.txw2.Document;
import com.thoughtworks.xstream.XStream;
public class WeixinUtils {
public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
System.out.println(xstream.toXML(textMessage));
return xstream.toXML(textMessage);
}
public static String imageMessageToXml(ImageMessage imageMessage){
XStream xstream = new XStream();
xstream.alias("xml", imageMessage.getClass());
return xstream.toXML(imageMessage);
}
public static String initImageMessage(String MediaId,String toUserName,String fromUserName){
String message = null;
Image image = new Image();
ImageMessage imageMessage = new ImageMessage();
image.setMediaId(MediaId);
imageMessage.setFromUserName(toUserName);
imageMessage.setToUserName(fromUserName);
imageMessage.setCreateTime(new Date().toString());
imageMessage.setImage(image);
imageMessage.setMsgType("image");
message = imageMessageToXml(imageMessage);
return message;
}
public static String initTextMessage(String content,String toUserName,String fromUserName){
String message = null;
TextMessage textMessage = new TextMessage();
textMessage.setFromUserName(toUserName);
textMessage.setToUserName(fromUserName);
textMessage.setCreateTime(new Date().toString());
textMessage.setContent(content);
textMessage.setMsgType("text");
message = textMessageToXml(textMessage);
return message;
}
public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
url = url.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.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=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = JSONObject.parseObject(result);
System.out.println(jsonObj);
String typeName = "media_id";
if(!"image".equals(type)){
typeName = type + "_media_id";
}
String mediaId = jsonObj.getString(typeName);
return mediaId;
}
}
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
public class Image {
private String MediaId;
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
}
public class ImageMessage extends Message{
private Image image;
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
}
public class Message {
private String ToUserName;
private String FromUserName;
private String CreateTime;
private String MsgType;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
}
public class TextMessage extends Message{
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}