1.要实现图片消息的回复,我们需要获取access_token,具体原因不累赘叙述,参考官网资料
2.为了方便我们后面调用相关方法,我们采用httpClient来实现,先完成2个工具方法,doGet及doPost方法,这里新建一个类WenXinUntil,由上图可以看出访问get方法需要传递grant_type、appid、secret这3个参数,为了方便后期代码灵活性,分别创建3个静态常量:
//get请求
public static JSONObject doGetStr(String url) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
return jsonObject;
}
//post请求
public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
JSONObject jsonObject = null;
httpost.setEntity(new StringEntity(outStr,"UTF-8"));
HttpResponse response = client.execute(httpost);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.fromObject(result);
return jsonObject;
}
3.创建好相关方法后,访问
所以在WenXinUntil类在添加一个获取url地址的常量
创建获取access_token相关方法:
//获取accessToken
public static AccessToken getAccessToken() throws ParseException, IOException{
AccessToken token = new AccessToken();
String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = doGetStr(url);
if(jsonObject!=null){
token.setToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
}
return token;
}
4.下面我们来看回复图片消息数据结构
要回复图片消息,这时候我们就需要上传临时素材:
在工具类中新增常量及上传文件并获取media_id的方法:
//文件上传并获取上传文件的mediaId
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 = UPLOAD_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);
//文件正文部分
//把文件已流文件的方式 推入到url中
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 {
//定义BufferedReader输入流来读取URL的响应
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.fromObject(result);
System.out.println(jsonObj);
//如果是图片消息,直接返回media_id,如果是其他类型的消息,会返回一个消息类型+media_id
String typeName = "media_id";
if(!"image".equals(type)){
typeName = type + "_media_id";
}
String mediaId = jsonObj.getString(typeName);
return mediaId;
}
5.写一个测试方法,进行测试调通
代码:
public class WeixinTest {
public static void main(String[] args){
try {
AccessToken token = WenXinUntil.getAccessToken();
String filePath = "D:/image/123.jpg";
String mediaId = WenXinUntil.upload(filePath,token.getToken(), "image");
System.out.println("票据"+token.getToken());
System.out.println("有效时间"+token.getExpiresIn());
System.out.println(mediaId);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行main方法,得到token以及mediaId,测试成功,运行成功截图如下:
6.我们再来看一下回复图片消息数据结构,里面包含了一个Image消息类型
所有这里我们先新建一个Image类,只有一个MediaId属性:
public class Image {
private String MediaId;
set、get方法略。。。
}
再新建一个图片消息组装实体类,包含Image:
public class ImageMessage extends BaseMessage{
private Image Image;
set/get方法略。。。
}
7.在我们消息回复工具类MessageUtil中去组装回复图文消息相关方法,同上先需要把图片消息转化为XML格式数据,以及把XML格式消息转化为图片消息:
//图片消息转为XML格式数据
public static String imageMessageToXml(ImageMessage imageMessage){
XStream xstream = new XStream();
xstream.alias("xml", imageMessage.getClass());
return xstream.toXML(imageMessage);
}
//组装图片消息
public static String initImageMessage(String toUserName,String fromUserName){
String message = null;
Image image = new Image();
image.setMediaId("3kEkpVGVVFp6awU8L-rvmkoUap9rSb4gW77v1z6jYM4b3-tNbIc_wtG5P2Q8mHpc");//这里为刚刚我们测试时候获取到的MediaId
ImageMessage imageMessage = new ImageMessage();
imageMessage.setFromUserName(toUserName);
imageMessage.setToUserName(fromUserName);
imageMessage.setMsgType(MESSAGE_IMAGE);
imageMessage.setCreateTime(new Date().getTime());
imageMessage.setImage(image);
message = imageMessageToXml(imageMessage);
return message;
}
8.在servlet中补全我们需要回复的内容
9.启动项目,查看运行效果如下(这里我们要用测试账号来,个人没有权限):
至此,回复图片消息完成!