zoukankan      html  css  js  c++  java
  • java微信接口之三—上传多媒体文件

    一、微信上传多媒体接口简介

      1、请求:该请求是使用post提交from来实现的,我们可以在网页上进行表单提交来实现。地址为: 

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

      其中ACCESS_TOKEN是我们动态获取的,TYPE是 媒体文件类型。有以下几种类型:,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)

      post提交的数据就是文件本身,其中该文件对应的name值(微信服务器根据该值获取文件,input 标签的name值)为media(规定值)。

      2、响应:该响应也是以json方式返回的

      正确的时候返回的数据:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}  

      TYPE为我们传递给服务器的类型,media_id就是文件id,created_at表示创建的时间。

      错误的时候返回的数据:{"errcode":40004,"errmsg":"invalid media type"}

      errcode,为错误代码,errmsg为错误信息

      具体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

    二、关于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文件如下:

    三、代码实现

      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。

  • 相关阅读:
    Struts2 MVC基础介绍
    【转载】Linux下安装、配置、启动Apache
    网易校招编程题
    libevent中evmap实现(哈希表)
    libevent源码阅读笔记(一):libevent对epoll的封装
    Linux进程间通信总结
    【转载】Ubuntu 12.04 LTS 中文输入法的安装
    转载 正则表达式30分钟入门教程
    简明Vim练级攻略
    【转载】C++基本功和 Design Pattern系列 ctor & dtor
  • 原文地址:https://www.cnblogs.com/always-online/p/3870733.html
Copyright © 2011-2022 走看看