模拟浏览器post请求 用java写上传文件后台

公众号在使用接口时,对多媒体文件、多媒体消息的获取和调用等操作,是通过media_id来进行的。通过本接口,公众号可以上传或下载多媒体文件。但请注意,每个多媒体文件(media_id)会在上传、用户发送到微信服务器3天后自动删除,以节省服务器资源。

公众号可调用本接口来上传图片、语音、视频等文件到微信服务器,上传后服务器会返回对应的media_id,公众号此后可根据该media_id来获取多媒体。请注意,media_id是可复用的,调用该接口需http协议。

接口调用请求说明

[plain]  view plain  copy
 print ?
  1. http请求方式: POST/FORM  
  2. http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE  
  3. 调用示例(使用curl命令,用FORM表单方式上传一个多媒体文件):  
  4. curl -F media=@test.jpg "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"  


首先封装一个HttpPostUtil类,专门负责文件上传请求及一些参数的设置(此处可以理解为上传文件表单参数设置和connection的一些必须设置)、字符编码,文件类型等。

HttpPostUtil类代码:

[java]  view plain  copy
 print ?
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.DataOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8. import java.net.URLEncoder;  
  9. import java.util.HashMap;  
  10. import java.util.Iterator;  
  11. import java.util.Set;  
  12.   
  13. /** 
  14.  *  
  15.  * @author Sunlight 
  16.  *  
  17.  */  
  18. public class HttpPostUtil {  
  19.     private URL url;  
  20.     private HttpURLConnection conn;  
  21.     private String boundary = "--------httppost123";  
  22.     private HashMap<String, String> textParams = new HashMap<String, String>();  
  23.     private HashMap<String, File> fileparams = new HashMap<String, File>();  
  24.     private DataOutputStream outputStream;  
  25.   
  26.     public HttpPostUtil(String url) throws Exception {  
  27.         this.url = new URL(url);  
  28.     }  
  29.   
  30.     /** 
  31.      * 重新设置要请求的服务器地址,即上传文件的地址。 
  32.      *  
  33.      * @param url 
  34.      * @throws Exception 
  35.      */  
  36.     public void setUrl(String url) throws Exception {  
  37.         this.url = new URL(url);  
  38.     }  
  39.   
  40.     /** 
  41.      * 增加一个普通字符串数据到form表单数据中 
  42.      *  
  43.      * @param name 
  44.      * @param value 
  45.      */  
  46.     public void addParameter(String name, String value) {  
  47.         textParams.put(name, value);  
  48.     }  
  49.   
  50.     /** 
  51.      * 增加一个文件到form表单数据中 
  52.      *  
  53.      * @param name 
  54.      * @param value 
  55.      */  
  56.     public void addParameter(String name, File value) {  
  57.         fileparams.put(name, value);  
  58.     }  
  59.   
  60.     /** 
  61.      * 清空所有已添加的form表单数据 
  62.      */  
  63.     public void clearAllParameters() {  
  64.         textParams.clear();  
  65.         fileparams.clear();  
  66.     }  
  67.   
  68.     /** 
  69.      * 发送数据到服务器,返回一个字节包含服务器的返回结果的数组 
  70.      *  
  71.      * @return 
  72.      * @throws Exception 
  73.      */  
  74.     public String send() throws Exception {  
  75.         initConnection();  
  76.         conn.connect();  
  77.         outputStream = new DataOutputStream(conn.getOutputStream());  
  78.         writeFileParams();  
  79.         writeStringParams();  
  80.         paramsEnd();  
  81.         int code = conn.getResponseCode();  
  82.         if (code == 200) {  
  83.             InputStream in = conn.getInputStream();  
  84.             ByteArrayOutputStream out = new ByteArrayOutputStream();  
  85.             byte[] buf = new byte[1024 * 8];  
  86.             int len;  
  87.             while ((len = in.read(buf)) != -1) {  
  88.                 out.write(buf, 0, len);  
  89.             }  
  90.             conn.disconnect();  
  91.             String s = new String(out.toByteArray(), "utf-8");  
  92.             return s;  
  93.         }  
  94.         return null;  
  95.     }  
  96.   
  97.     /** 
  98.      * 文件上传的connection的一些必须设置 
  99.      *  
  100.      * @throws Exception 
  101.      */  
  102.     private void initConnection() throws Exception {  
  103.         conn = (HttpURLConnection) this.url.openConnection();  
  104.         conn.setDoOutput(true);  
  105.         conn.setUseCaches(false);  
  106.         conn.setConnectTimeout(10000); // 连接超时为10秒  
  107.         conn.setRequestMethod("POST");  
  108.         conn.setRequestProperty("Content-Type""multipart/form-data; boundary=" + boundary);  
  109.     }  
  110.   
  111.     /** 
  112.      * 普通字符串数据 
  113.      *  
  114.      * @throws Exception 
  115.      */  
  116.     private void writeStringParams() throws Exception {  
  117.         Set<String> keySet = textParams.keySet();  
  118.         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
  119.             String name = it.next();  
  120.             String value = textParams.get(name);  
  121.             outputStream.writeBytes("--" + boundary + "\r\n");  
  122.             outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");  
  123.             outputStream.writeBytes("\r\n");  
  124.             outputStream.writeBytes(encode(value) + "\r\n");  
  125.         }  
  126.     }  
  127.   
  128.     /** 
  129.      * 文件数据 
  130.      *  
  131.      * @throws Exception 
  132.      */  
  133.     private void writeFileParams() throws Exception {  
  134.         Set<String> keySet = fileparams.keySet();  
  135.         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
  136.             String name = it.next();  
  137.             File value = fileparams.get(name);  
  138.             outputStream.writeBytes("--" + boundary + "\r\n");  
  139.             outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + encode(value.getName()) + "\"\r\n");  
  140.             outputStream.writeBytes("Content-Type: " + getContentType(value) + "\r\n");  
  141.             outputStream.writeBytes("\r\n");  
  142.             outputStream.write(getBytes(value));  
  143.             outputStream.writeBytes("\r\n");  
  144.         }  
  145.     }  
  146.   
  147.     /** 
  148.      * 获取文件的上传类型,图片格式为image/png,image/jpeg等。非图片为application /octet-stream 
  149.      *  
  150.      * @param f 
  151.      * @return 
  152.      * @throws Exception 
  153.      */  
  154.     private String getContentType(File f) throws Exception {  
  155.         return "application/octet-stream";  
  156.     }  
  157.   
  158.     /** 
  159.      * 把文件转换成字节数组 
  160.      *  
  161.      * @param f 
  162.      * @return 
  163.      * @throws Exception 
  164.      */  
  165.     private byte[] getBytes(File f) throws Exception {  
  166.         FileInputStream in = new FileInputStream(f);  
  167.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  168.         byte[] b = new byte[1024];  
  169.         int n;  
  170.         while ((n = in.read(b)) != -1) {  
  171.             out.write(b, 0, n);  
  172.         }  
  173.         in.close();  
  174.         return out.toByteArray();  
  175.     }  
  176.   
  177.     /** 
  178.      * 添加结尾数据 
  179.      *  
  180.      * @throws Exception 
  181.      */  
  182.     private void paramsEnd() throws Exception {  
  183.         outputStream.writeBytes("--" + boundary + "--" + "\r\n");  
  184.         outputStream.writeBytes("\r\n");  
  185.     }  
  186.   
  187.     /** 
  188.      * 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码 
  189.      *  
  190.      * @param value 
  191.      * @return 
  192.      * @throws Exception 
  193.      */  
  194.     private String encode(String value) throws Exception {  
  195.         return URLEncoder.encode(value, "UTF-8");  
  196.     }     
  197. }  
上传测试方法(可以在自己项目中上传文件到一些第三方提供的平台):
[java]  view plain  copy
 print ?
  1. /** 
  2.  * 使用方法示例 
  3.  * 此方法需要修改成自己上传地址才可上传成功 
  4.  * @param args 
  5.  * @throws Exception 
  6.  */  
  7. public static void test(String[] args) throws Exception {  
  8.     File file=new File("D\\up.jpg");  
  9.     //此处修改为自己上传文件的地址  
  10.     HttpPostUtil post = new HttpPostUtil("http://www.omsdn.cn");   
  11.     //此处参数类似 curl -F media=@test.jpg  
  12.     post.addParameter("media", file);  
  13.     post.send();  
  14. }  

上传文件方法封装好后,微信公众号上传文件类调用,此处需要JSON包(json-lib-2.2.3-jdk13.jar):

[java]  view plain  copy
 print ?
  1. import java.io.File;  
  2. import cn.<span style="font-family:FangSong_GB2312;">xx</span>.wechat.model.MdlUpload;  
  3. import cn.<span style="font-family:FangSong_GB2312;">xx</span>.wechat.model.Result;  
  4. import net.sf.json.JSONObject;  
  5. /** 
  6.  *  
  7.  * @author Sunlight 
  8.  * 
  9.  */  
  10. public class FileUpload {  
  11.     private static final String upload_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";  
  12.       
  13.     /** 
  14.      * 上传文件 
  15.      *  
  16.      * @param accessToken 
  17.      * @param type 
  18.      * @param file 
  19.      * @return 
  20.      */  
  21.     public static Result<MdlUpload> Upload(String accessToken, String type, File file) {  
  22.         Result<MdlUpload> result = new Result<MdlUpload>();  
  23.         String url = upload_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);  
  24.         JSONObject jsonObject;  
  25.         try {  
  26.             HttpPostUtil post = new HttpPostUtil(url);  
  27.             post.addParameter("media", file);  
  28.             String s = post.send();  
  29.             jsonObject = JSONObject.fromObject(s);  
  30.             if (jsonObject.containsKey("media_id")) {  
  31.                 MdlUpload upload=new MdlUpload();  
  32.                 upload.setMedia_id(jsonObject.getString("media_id"));  
  33.                 upload.setType(jsonObject.getString("type"));  
  34.                 upload.setCreated_at(jsonObject.getString("created_at"));  
  35.                 result.setObj(upload);  
  36.                 result.setErrmsg("success");  
  37.                 result.setErrcode("0");  
  38.             } else {  
  39.                 result.setErrmsg(jsonObject.getString("errmsg"));  
  40.                 result.setErrcode(jsonObject.getString("errcode"));  
  41.             }  
  42.         } catch (Exception e) {  
  43.             e.printStackTrace();  
  44.             result.setErrmsg("Upload Exception:"+e.toString());  
  45.         }  
  46.         return result;  
  47.     }  
  48. }  

调用方法需要引用2个Model类(返回结果类和上传文件类型类):

返回结果类:

[java]  view plain  copy
 print ?
  1. package cn.<span style="font-family:FangSong_GB2312;">xx</span>.wechat.model;  
  2.   
  3. public class Result<T> {  
  4.     private T obj;  
  5.     private String errcode;  
  6.     private String errmsg;  
  7.     public T getObj() {  
  8.         return obj;  
  9.     }  
  10.     public void setObj(T obj) {  
  11.         this.obj = obj;  
  12.     }  
  13. <span style="font-family:FangSong_GB2312;">        </span>public String getErrcode() {  
  14.         return errcode;  
  15.     }  
  16.      public void setErrcode(String errcode) {  
  17.          this.errcode = errcode;  
  18.      }  
  19.     public String getErrmsg() {  
  20.          return errmsg;  
  21.     }  
  22.     public void setErrmsg(String errmsg) {  
  23.          this.errmsg = errmsg;  
  24.     }  
  25.       
  26. }  

文件上传返回文件类型类:
[java]  view plain  copy
 print ?
  1. package cn.<span style="font-family:FangSong_GB2312;">xx</span>.wechat.model;  
  2.   
  3. public class MdlUpload {  
  4.     private String type;  
  5.     private String media_id;  
  6.     private String created_at;  
  7.     public String getType() {  
  8.         return type;  
  9.     }  
  10.       public void setType(String type) {  
  11.          this.type = type;  
  12.       }  
  13.     public String getMedia_id() {  
  14.           return media_id;  
  15.     }  
  16.      public void setMedia_id(String mediaId) {  
  17.           media_id = mediaId;  
  18.     }  
  19.     public String getCreated_at() {  
  20.           return created_at;  
  21.       }  
  22.      public void setCreated_at(String createdAt) {  
  23.           created_at = createdAt;  
  24.     }  
  25.       public MdlUpload() {  
  26.          super();  
  27.      }  
  28.     @Override  
  29.     public String toString() {  
  30.         return "MdlUpload [created_at=" + created_at + ", media_id=" + media_id + ", type=" + type + "]";  
  31.      }  
  32.       
  33.       
  34. }  

最后微信上传文件测试方法:
[java]  view plain  copy
 print ?
  1. @Test  
  2.     public void testUpload() {  
  3.         File file=new File("E:\\Tulips.jpg");  
  4.         System.err.println(file.getName());  
  5.         Result<MdlUpload> result=FileUpload .Upload("image", file);  
  6.         System.out.println("Errcode="+result.getErrcode()+"\tErrmsg="+result.getErrmsg());  
  7.         System.out.println(result.getObj().toString());  
  8.     }  

测试结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
使用curl提交POST请求的示例命令如下: ```shell curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8080/api/endpoint ``` 其中,`-X POST`表示使用POST方法,`-H "Content-Type: application/json"`表示请求头中的Content-Type为application/json,`-d '{"key1":"value1", "key2":"value2"}'`表示请求体中的数据为JSON格式的键值对,`http://localhost:8080/api/endpoint`表示请求的URL。 对于Java后端,可以使用Spring Boot框架来编POST请求的接口。示例代码如下: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping("/api/endpoint") public String handlePostRequest(@RequestBody MyRequestData requestData) { // 处理POST请求的逻辑 // 可以通过requestData获取请求体中的数据 // 返回处理结果 return "Success"; } } public class MyRequestData { private String key1; private String key2; // getter和setter方法省略 // 可以根据实际需求定义其他字段 } ``` 在上述代码中,`@PostMapping("/api/endpoint")`注解表示该方法处理POST请求,并指定了请求的URL为`/api/endpoint`。`@RequestBody`注解表示将请求体中的数据映射到`MyRequestData`对象中,可以通过该对象获取请求体中的数据。处理逻辑可以根据实际需求进行编,最后返回处理结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值