1 try { 2 3 //声明分割线 4 String boundary="-----"; 5 6 //准备前期 7 File file=new File(filePath); 8 URL url=new URL("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=Z_dtsiJWpgghBANNad1B9DS4sgfE9zOLmwIffYmDXDKs4ZWr6wmhX6xYNanplgB8BVsER8JFtRAnJlyc24kDiSfQwMIzIISbWKLHCkQU9ZhXYNokaZchKmA4QOtH6VoBTSBjAAAEDM&type=image"); 9 URLConnection urlConnection=url.openConnection(); 10 urlConnection.setDoInput(true); 11 urlConnection.setDoOutput(true); 12 urlConnection.setUseCaches(false); 13 urlConnection.setRequestProperty("Connection","Keep-Alive"); 14 urlConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary); 15 urlConnection.setRequestProperty("Content-Length",String.valueOf(file.length())); 16 17 //获取文件输入流 18 InputStream inputStream=new FileInputStream(file); 19 //获取响应输出流 20 OutputStream outputStream = urlConnection.getOutputStream(); 21 22 //准备写入头信息 23 outputStream.write((boundary+"--\r\n").getBytes()); 24 outputStream.write(("Content-Disposition:form-data;name=\"media\";filename=\""+file.getName()+"\"\r\n").getBytes()); 25 outputStream.write(("Content-Type:image/jpeg\r\n\r\n").getBytes()); 26 //准备循环写入 文件流 27 byte[] b=new byte[1024]; 28 int l; 29 while((l=inputStream.read(b,0,b.length))!=-1){ 30 outputStream.write(b,0,l); 31 } 32 outputStream.write(("\r\n"+boundary+"--\r\n").getBytes()); 33 34 //关闭 35 outputStream.flush(); 36 outputStream.close(); 37 inputStream.close(); 38 39 urlConnection.connect(); 40 41 InputStream is=urlConnection.getInputStream(); 42 int c; 43 while((c=is.read())!=-1){ 44 System.out.print((char)c); 45 } 46 is.close(); 47 } catch (MalformedURLException e) { 48 e.printStackTrace(); 49 } catch (IOException e) { 50 e.printStackTrace(); 51 }
特别注意写入文件数据的时候,首尾都需要有分割线,并且分割线比RequestProperty里的Content-Type里的分割线多--个,并且注意换行
其次就是上传的name的值为media字符串
再其次注意请求所附带的参数