本文实例为大家分享了java实现上传网络图片到微信临时素材的具体代码,供大家参考,具体内容如下
包org.afuos.playcontrol.service; 进口com.alibaba.fastjson.JSON; 进口com.alibaba.fastjson.JSONObject; 进口. io . *; 进口java.net.HttpURLConnection; 进口java.net.URL;/* * *由Mohon”; 字符串文件名=urlPath.substring (urlPath.lastIndexOf (“/? + 1);//获取网络图片 URL mediaUrl=新的URL (urlPath); HttpURLConnection meidaConn=(HttpURLConnection) mediaUrl.openConnection (); meidaConn.setDoOutput(真正的); meidaConn.setRequestMethod(“获得”);/* * *第一部分 */URL urlObj=新网址(URL); HttpURLConnection con=(HttpURLConnection) urlObj.openConnection (); con.setRequestMethod(“文章”);//以发布方式提交表单,默认得到方式 con.setDoInput(真正的); con.setDoOutput(真正的); con.setUseCaches(假);//发布方式不能使用缓存//设置请求头信息 con.setRequestProperty(“连接”、“维生”); con.setRequestProperty(“字符集”、“utf - 8”);//设置边界 字符串边界=" - - - - - - - - - - - " + System.currentTimeMillis (); con.setRequestProperty(“内容类型”、“多部分/格式;边界边界=" +);//请求正文信息//第一部分: StringBuilder某人=new StringBuilder (); sb.append (“-”);//必须多两道线 sb.append(边界); sb.append (" \ r \ n "); sb.append(“附加项:格式;name=\ "媒体\”;文件名=\”“+文件名+”\“\ r \ n”); sb.append(“内容类型:应用程序/八进制\ r \ n \ r \ n”); byte []=sb.toString负责人().getBytes (“utf - 8”);//获得输出流 OutputStream=new DataOutputStream (con.getOutputStream ());//输出表头 out.write(头);//文件正文部分//把文件已流文件的方式推入到url中 DataInputStream=new DataInputStream (meidaConn.getInputStream ()); int字节=0; byte [] bufferOut=新字节[1024]; 在((字节=in.read (bufferOut)) !=1) { 出去了。写(bufferOut 0字节); } in.close ();//结尾部分 脚byte []=(“\ r \ n——“+边界+”——\ r \ n”) .getBytes (" utf - 8 ");//定义最后数据分隔线 out.write(脚); out.flush (); out.close (); meidaConn.disconnect (); StringBuffer缓冲=new StringBuffer (); BufferedReader读者=零; 尝试{//定义BufferedReader输入流来读取URL的响应 读者=new BufferedReader(新InputStreamReader (con.getInputStream ())); 字符串行=零; 在((=reader.readLine行())!=null) { buffer.append(线); } 如果(结果==null) { 结果=buffer.toString (); } }捕捉(IOException e) { log.info(“发送帖子请求出现异常! {}”,e); e.printStackTrace (); 把新IOException(“数据读取异常”); 最后}{ 如果(读者!=null) { reader.close (); } } JSONObject jsonObj=JSON.parseObject(结果); log.info (“getMediaId jsonObj: {}”, jsonObj); 返回jsonObj.getString (“media_id”); } }
UploadPicToWx.java
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。