本文實例講述了java調用微信客服消息實現發貨通知的方法。分享給大家供大家參考,具體如下:
微信文檔地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547&token=&lang=zh_cn
個人說明:這是一個樣例,微信客戶消息有很多種,我現在用的是公眾號發送消息。樣子如下圖。
說明:下面開始代碼部分了。
1.首先看微信文檔。這里才是我們需要的
這里是說發消息要post請求這個接口:https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=access_token
但是這個接口后面需要帶一個參數access_token。
下面先獲取access_token。
1
2
3
4
5
6
7
8
9
10
11
12
|
//這里的weixinutil.getaccess_token()方法,放在下面。 string atoken = weixinutil.getaccess_token( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +你的appid+ "&secret=" +你的appsecret+ "" ); system.out.println( "這里是atoken" +atoken); string[] tokenone = atoken.split( ":" ); string[] token = tokenone[ 1 ].split( "," ); char [] stringarr = token[ 0 ].tochararray(); string token3 = "" ; for ( int i= 1 ;i<stringarr.length- 1 ;i++){ string token2 = string.valueof(stringarr[i]); token3 += token2; } system.out.println( "這里是access_token" +token3); |
獲取到一個access_token,然后就可以加入到微信請求中
1
2
3
4
5
6
7
8
9
10
11
|
//這里就是一個微信請求,首先用string放著 string tokenurl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" +token3; //首先確定是發送文字消息,還是圖文消息,這里是手寫的json數據. //發送文字消息,無連接 string json = "{\"touser\":\"這里是openid\",\"msgtype\":\"text\",\"text\":{\"content\":\"hello world\"}}" ; //圖文消息,有鏈接連接 string jsonpic = "{\"touser\":\"" +這里是openid+ "\"," + "\"msgtype\":\"news\",\"news\":{\"articles\":[" + "{\"title\":\"helloworld\",\"url\":\"要跳轉的鏈接" }]}}"; system.out.println( "這里是json" +jsonpic); //請求方法,然后放回ok 成功,否則錯誤。這里這個請求方法在下邊 string xmlstr = httpkit.post(tokenurl,jsonpic); system.out.println( "這里是xmlstr" +xmlstr); |
說明:weixinutil.getaccess_token()
方法。我放整個類了。改包名,只需要導入兩個包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.uitrs.weixin; import java.net.httpurlconnection; import java.net.url; public class weixinutil { //傳入url public static string getaccess_token(string url) { string accesstoken = null ; try { url urlget = new url(url); httpurlconnection http = (httpurlconnection) urlget .openconnection(); http.setrequestmethod( "get" ); // 必須是get方式請求 http.setrequestproperty( "content-type" , "application/x-www-form-urlencoded" ); http.setdooutput( true ); http.setdoinput( true ); system.setproperty( "sun.net.client.defaultconnecttimeout" , "30000" ); // 連接超時30秒 system.setproperty( "sun.net.client.defaultreadtimeout" , "30000" ); // 讀取超時30秒 http.connect(); inputstream is = http.getinputstream(); int size = is.available(); byte [] jsonbytes = new byte [size]; is.read(jsonbytes); accesstoken = new string(jsonbytes, "utf-8" ); system.out.println(accesstoken); is.close(); } catch (exception e) { e.printstacktrace(); } return accesstoken; } } |
說明:httpkit.post();
方法,我放整個類了。這個類我用的是導入
1
|
import com.jfinal.kit.httpkit; |
這個包到了jfinal的包。出自下面三個包當中,具體我也不清楚了
1.jfinal-2.2.jar (應該是這個)
2.jfinal-2.2-bin-with-src.jar
3.jfinal-weixin-1.7-bin-with-src.jar
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/qq_29057491/article/details/53419262