java微信接口之三—上傳多媒體文件

1、微信上傳多媒體接口簡介php

  一、請求:該請求是使用post提交from來實現的,咱們能夠在網頁上進行表單提交來實現。地址爲: java

  http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPEapache

  其中ACCESS_TOKEN是咱們動態獲取的,TYPE是 媒體文件類型。有如下幾種類型:,分別有圖片(image)、語音(voice)、視頻(video)和縮略圖(thumb)json

  post提交的數據就是文件自己,其中該文件對應的name值(微信服務器根據該值獲取文件,input 標籤的name值)爲media(規定值)。api

  二、響應:該響應也是以json方式返回的服務器

  正確的時候返回的數據:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}  微信

  TYPE爲咱們傳遞給服務器的類型,media_id就是文件id,created_at表示建立的時間。ide

  錯誤的時候返回的數據:{"errcode":40004,"errmsg":"invalid media type"}post

  errcode,爲錯誤代碼,errmsg爲錯誤信息jsonp

  具體api可查看:http://mp.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E4%B8%8B%E8%BD%BD%E5%A4%9A%E5%AA%92%E4%BD%93%E6%96%87%E4%BB%B6

2、關於java代碼的調用

  在前臺進行form提交很容易實現,如今要使用java代碼進行表達提交,須要使用到commons-httpclient。httpclient以前在apache是做爲commons項目的子項目,而之後才升級到apache的頂級項目。這裏須要使用到的就是以前在做爲commons子項目的版本,使用的版本爲commons-httpclient-3.0。下載地址爲:http://archive.apache.org/dist/httpcomponents/commons-httpclient/3.0/binary/

須要引入的jar文件以下:

3、代碼實現

  1 import java.io.File;
  2 
  3 import org.apache.commons.httpclient.methods.PostMethod;
  4 import org.apache.commons.httpclient.methods.multipart.FilePart;
  5 import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
  6 import org.apache.commons.httpclient.methods.multipart.Part;
  7 import org.apache.http.HttpEntity;
  8 import org.apache.http.HttpResponse;
  9 import org.apache.http.HttpStatus;
 10 import org.apache.http.client.HttpClient;
 11 import org.apache.http.client.methods.HttpGet;
 12 import org.apache.http.impl.client.DefaultHttpClient;
 13 import org.apache.http.util.EntityUtils;
 14 
 15 import com.google.gson.JsonObject;
 16 import com.google.gson.JsonParser;
 17 
 18 public class Test
 19 {
 20     public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 獲取access
 21     public static final String UPLOAD_IMAGE_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload";// 上傳多媒體文件
 22     public static final String APP_ID = "wxa549b28c24cf341e";
 23     public static final String SECRET = "78d8a8cd7a4fa700142d06b96bf44a37";
 24 
 25     /**
 26      * 上傳多媒體文件
 27      * 
 28      * @param url
 29      *            訪問url
 30      * @param access_token
 31      *            access_token
 32      * @param type
 33      *            文件類型
 34      * @param file
 35      *            文件對象
 36      * @return
 37      */
 38     public static String uploadImage(String url, String access_token,
 39             String type, File file)
 40     {
 41         org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
 42         String uploadurl = String.format("%s?access_token=%s&type=%s", url,
 43                 access_token, type);
 44         PostMethod post = new PostMethod(uploadurl);
 45         post
 46                 .setRequestHeader(
 47                         "User-Agent",
 48                         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
 49         post.setRequestHeader("Host", "file.api.weixin.qq.com");
 50         post.setRequestHeader("Connection", "Keep-Alive");
 51         post.setRequestHeader("Cache-Control", "no-cache");
 52         String result = null;
 53         try
 54         {
 55             if (file != null && file.exists())
 56             {
 57                 FilePart filepart = new FilePart("media", file, "image/jpeg",
 58                         "UTF-8");
 59                 Part[] parts = new Part[] { filepart };
 60                 MultipartRequestEntity entity = new MultipartRequestEntity(
 61                         parts,
 62 
 63                         post.getParams());
 64                 post.setRequestEntity(entity);
 65                 int status = client.executeMethod(post);
 66                 if (status == HttpStatus.SC_OK)
 67                 {
 68                     String responseContent = post.getResponseBodyAsString();
 69                     JsonParser jsonparer = new JsonParser();// 初始化解析json格式的對象
 70                     JsonObject json = jsonparer.parse(responseContent)
 71                             .getAsJsonObject();
 72                     if (json.get("errcode") == null)// {"errcode":40004,"errmsg":"invalid media type"}
 73                     { // 上傳成功  {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
 74                         result = json.get("media_id").getAsString();
 75                     }
 76                 }
 77             }
 78         }
 79         catch (Exception e)
 80         {
 81             e.printStackTrace();
 82         }
 83         finally
 84         {
 85             return result;
 86         }
 87     }
 88 
 89     public static void main(String[] args) throws Exception
 90     {
 91         String accessToken = getToken(GET_TOKEN_URL, APP_ID, SECRET);// 獲取token在微信接口之一中的方法獲取token
 92         if (accessToken != null)// token成功獲取
 93         {
 94             System.out.println(accessToken);
 95             File file = new File("f:" + File.separator + "2000.JPG"); // 獲取本地文件
 96             String id = uploadImage(UPLOAD_IMAGE_URL, accessToken, "image",
 97                     file);// 上傳文件
 98             if (id != null)
 99                 System.out.println(id);
100         }
101     }
102 
103 }

上傳成功就會打印該文件id。

相關文章
相關標籤/搜索