java实现上传网络图片到微信临时素材
程序员文章站
2024-02-21 13:24:10
本文实例为大家分享了java实现上传网络图片到微信临时素材的具体代码,供大家参考,具体内容如下
package org.afuos.playcontrol.ser...
本文实例为大家分享了java实现上传网络图片到微信临时素材的具体代码,供大家参考,具体内容如下
package org.afuos.playcontrol.service; import com.alibaba.fastjson.json; import com.alibaba.fastjson.jsonobject; import java.io.*; import java.net.httpurlconnection; import java.net.url; /** * created by mohon on 2017/8/10. */ public class uploadpictowx { /** * 网络图片上传到微信服务器 * * @param urlpath 图片路径 * @return jsonobject * @throws exception */ public string getmediaidfromurl(string urlpath, string filetype) throws exception { string result = null; string url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token= access_token &type=" + filetype + ""; string filename = urlpath.substring(urlpath.lastindexof("/") + 1); // 获取网络图片 url mediaurl = new url(urlpath); httpurlconnection meidaconn = (httpurlconnection) mediaurl.openconnection(); meidaconn.setdooutput(true); meidaconn.setrequestmethod("get"); /** * 第一部分 */ url urlobj = new url(url); httpurlconnection con = (httpurlconnection) urlobj.openconnection(); con.setrequestmethod("post"); // 以post方式提交表单,默认get方式 con.setdoinput(true); con.setdooutput(true); con.setusecaches(false); // post方式不能使用缓存 // 设置请求头信息 con.setrequestproperty("connection", "keep-alive"); con.setrequestproperty("charset", "utf-8"); // 设置边界 string boundary = "----------" + system.currenttimemillis(); con.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); // 请求正文信息 // 第一部分: stringbuilder sb = new stringbuilder(); sb.append("--"); // 必须多两道线 sb.append(boundary); sb.append("\r\n"); sb.append("content-disposition: form-data;name=\"media\";filename=\"" + filename + "\"\r\n"); sb.append("content-type:application/octet-stream\r\n\r\n"); byte[] head = sb.tostring().getbytes("utf-8"); // 获得输出流 outputstream out = new dataoutputstream(con.getoutputstream()); // 输出表头 out.write(head); // 文件正文部分 // 把文件已流文件的方式 推入到url中 datainputstream in = new datainputstream(meidaconn.getinputstream()); int bytes = 0; byte[] bufferout = new byte[1024]; while ((bytes = in.read(bufferout)) != -1) { out.write(bufferout, 0, bytes); } in.close(); // 结尾部分 byte[] foot = ("\r\n--" + boundary + "--\r\n").getbytes("utf-8");// 定义最后数据分隔线 out.write(foot); out.flush(); out.close(); meidaconn.disconnect(); stringbuffer buffer = new stringbuffer(); bufferedreader reader = null; try { // 定义bufferedreader输入流来读取url的响应 reader = new bufferedreader(new inputstreamreader(con.getinputstream())); string line = null; while ((line = reader.readline()) != null) { buffer.append(line); } if (result == null) { result = buffer.tostring(); } } catch (ioexception e) { log.info("发送post请求出现异常! {}", e); e.printstacktrace(); throw new ioexception("数据读取异常"); } finally { if (reader != null) { reader.close(); } } jsonobject jsonobj = json.parseobject(result); log.info("getmediaid jsonobj: {}", jsonobj); return jsonobj.getstring("media_id"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。