使用httpclient4.3.2来实现微信临时素材的上传
生活随笔
收集整理的這篇文章主要介紹了
使用httpclient4.3.2来实现微信临时素材的上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ?一直在用java來做微信的二次開發,經過一段時間的沉淀總算有了一點門路。其實用java這種強大的語言來做微信的二次開發是很簡單的事情。只要解決了加密、https請求的發送、xml的解析這些基本的操作后,用java來進行微信二次開發就變的容易了很多。
public static void httpsClient() throws Exception {// 獲得utf-8編碼的mbuilderMultipartEntityBuilder mBuilder = get_COMPATIBLE_Builder("UTF-8");/*** 原生的微信使用的url是https://api.weixin.qq.com/cgi-bin/media/upload?* access_token=##ACCESS_TOKEN##&type=##TYPE##* 一般都會使用這個把參數直接攜帶在url中。我個人不喜歡這樣,因為既然使用了httpclient,完全可以把參數* 設置在我們的body體中。所以我們使用的url是這樣的* https://api.weixin.qq.com/cgi-bin/media/upload 然后通過在body體中設置參數來設置* access_token和type這兩個字段* * */// 設置type,我這里用一個縮略圖來做實驗,所以type是thumbmBuilder.addTextBody("type", "thumb");// 設置access_token,mBuilder.addTextBody("access_token", getAccessToken());// 這里就是我要上傳到服務器的多媒體圖片mBuilder.addBinaryBody("media", getFile("d:/test.jpg"),ContentType.APPLICATION_OCTET_STREAM, getFile("d:/test.jpg").getName());// 建造我們的http多媒體對象HttpEntity he = mBuilder.build();// 建立一個sslcontext,這里我們信任任何的證書。SSLContext context = getTrustAllSSLContext();// 建立socket工廠SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(context);// 建立連接器CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(factory).build();try {// 得到一個post請求的實體HttpPost post = getMultipartPost();// 給請求添加參數post.setEntity(he);// 執行請求并獲得結果CloseableHttpResponse reponse = client.execute(post);try {// 獲得返回的內容HttpEntity entity = reponse.getEntity();// 輸出System.out.println(EntityUtils.toString(entity));// 消耗實體EntityUtils.consume(entity);} finally {// 關閉返回的reponsereponse.close();}} finally {// 關閉clientclient.close();}} private static String getBoundaryStr(String str) {return "------------" + str;}private static File getFile(String path) {return new File(path);}private static MultipartEntityBuilder get_COMPATIBLE_Builder(String charSet) {MultipartEntityBuilder result = MultipartEntityBuilder.create();result.setBoundary(getBoundaryStr("7da2e536604c8")).setCharset(Charset.forName(charSet)).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);return result;}private static String getAccessToken() {// 這里返回一個access_token,我在實際項目中是使用redis來緩存起來的。這里就直接返回了,要改成自己的哦return "PFKLPAJ6HqxylpsKM7CWUoFoKeQlvLRRfArUmR9QEji2uWIEh9qsbGQ0eEih8gsnKrtjoCME_PgPV2ut_Wt3XTNmoJLDycpjtID0KItfVk";}private static String getUrl() {return up_temporary_url;}private static HttpPost getMultipartPost() {/* 這里設置一些post的頭部信息,具體求百度吧 */HttpPost post = new HttpPost(getUrl());post.addHeader("Connection", "keep-alive");post.addHeader("Accept", "*/*");post.addHeader("Content-Type", "multipart/form-data;boundary="+ getBoundaryStr("7da2e536604c8"));post.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");return post;}private static SSLContext getTrustAllSSLContext() throws Exception {SSLContext context = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] arg0, String arg1)throws CertificateException {// 這一句就是信任任何的證書,當然你也可以去驗證微信服務器的真實性return true;}}).build();return context;}
這里我主要上傳一個用httpclient來實現多媒體素材上傳的例子。當然也可以使用urlconnection來實現該功能。但是httpclient要簡單的多也省心的多。廢話不錯,直接上代碼了,代碼注釋很詳細。
private static String up_temporary_url = "https://api.weixin.qq.com/cgi-bin/media/upload";
public static void httpsClient() throws Exception {// 獲得utf-8編碼的mbuilderMultipartEntityBuilder mBuilder = get_COMPATIBLE_Builder("UTF-8");/*** 原生的微信使用的url是https://api.weixin.qq.com/cgi-bin/media/upload?* access_token=##ACCESS_TOKEN##&type=##TYPE##* 一般都會使用這個把參數直接攜帶在url中。我個人不喜歡這樣,因為既然使用了httpclient,完全可以把參數* 設置在我們的body體中。所以我們使用的url是這樣的* https://api.weixin.qq.com/cgi-bin/media/upload 然后通過在body體中設置參數來設置* access_token和type這兩個字段* * */// 設置type,我這里用一個縮略圖來做實驗,所以type是thumbmBuilder.addTextBody("type", "thumb");// 設置access_token,mBuilder.addTextBody("access_token", getAccessToken());// 這里就是我要上傳到服務器的多媒體圖片mBuilder.addBinaryBody("media", getFile("d:/test.jpg"),ContentType.APPLICATION_OCTET_STREAM, getFile("d:/test.jpg").getName());// 建造我們的http多媒體對象HttpEntity he = mBuilder.build();// 建立一個sslcontext,這里我們信任任何的證書。SSLContext context = getTrustAllSSLContext();// 建立socket工廠SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(context);// 建立連接器CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(factory).build();try {// 得到一個post請求的實體HttpPost post = getMultipartPost();// 給請求添加參數post.setEntity(he);// 執行請求并獲得結果CloseableHttpResponse reponse = client.execute(post);try {// 獲得返回的內容HttpEntity entity = reponse.getEntity();// 輸出System.out.println(EntityUtils.toString(entity));// 消耗實體EntityUtils.consume(entity);} finally {// 關閉返回的reponsereponse.close();}} finally {// 關閉clientclient.close();}} private static String getBoundaryStr(String str) {return "------------" + str;}private static File getFile(String path) {return new File(path);}private static MultipartEntityBuilder get_COMPATIBLE_Builder(String charSet) {MultipartEntityBuilder result = MultipartEntityBuilder.create();result.setBoundary(getBoundaryStr("7da2e536604c8")).setCharset(Charset.forName(charSet)).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);return result;}private static String getAccessToken() {// 這里返回一個access_token,我在實際項目中是使用redis來緩存起來的。這里就直接返回了,要改成自己的哦return "PFKLPAJ6HqxylpsKM7CWUoFoKeQlvLRRfArUmR9QEji2uWIEh9qsbGQ0eEih8gsnKrtjoCME_PgPV2ut_Wt3XTNmoJLDycpjtID0KItfVk";}private static String getUrl() {return up_temporary_url;}private static HttpPost getMultipartPost() {/* 這里設置一些post的頭部信息,具體求百度吧 */HttpPost post = new HttpPost(getUrl());post.addHeader("Connection", "keep-alive");post.addHeader("Accept", "*/*");post.addHeader("Content-Type", "multipart/form-data;boundary="+ getBoundaryStr("7da2e536604c8"));post.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");return post;}private static SSLContext getTrustAllSSLContext() throws Exception {SSLContext context = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] arg0, String arg1)throws CertificateException {// 這一句就是信任任何的證書,當然你也可以去驗證微信服務器的真實性return true;}}).build();return context;}
這是最后返回的結果,主要就是那個thumb_media_id了,用這個就可以給用戶發送圖片消息了。
總結
以上是生活随笔為你收集整理的使用httpclient4.3.2来实现微信临时素材的上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝桥杯第六届国赛JAVA真题----奇怪
- 下一篇: NCRE四级网络工程师考题详解----三