上传本地图片至微信服务器并取得media_id

本文简洁介绍如何使用io流上传图片至微信服务器

不罗嗦,直接上代码。

	public class ImgUp {


	    public static String upload(String accessToken,String filePath,String type) throws IOException {
      
	        File file=new File(filePath);
	        if (!file.exists() || !file.isFile()){
	            throw new IOException("文件不存在");
	        }
	        String url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type="+type;

	        URL u=new URL(url);
	        HttpURLConnection connection= (HttpURLConnection) u.openConnection();
	        connection.setRequestMethod("POST");
	        connection.setDoInput(true);
	        connection.setDoOutput(true);
	        connection.setUseCaches(false);
	
	        connection.setRequestProperty("Connection","Keep-Alive");
	        connection.setRequestProperty("Charset","UTF-8");


	        String bound="-------"+ System.currentTimeMillis();
	        connection.setRequestProperty("Content-Type","multipart/form-data; boundary="+bound);

	        StringBuilder stringBuilder=new StringBuilder();

	        stringBuilder.append("--").append(bound).append("\r\n").
	                append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n").
	                append("Content-Type:application/octet-stream\r\n\r\n");
	        byte[] head=stringBuilder.toString().getBytes("utf-8");
	        OutputStream outputStream=new DataOutputStream(connection.getOutputStream());
	        outputStream.write(head);
	        DataInputStream in=new DataInputStream(new FileInputStream(file));
	        int bytes=0;
	        byte[] buffer=new byte[1024];
	        while((bytes=in.read(buffer))!=-1){
	            outputStream.write(buffer,0,bytes);
	        }
	        in.close();
	         byte[] foot=("\r\n--"+bound+"--\r\n").getBytes("utf-8");
	        outputStream.write(foot);
	        outputStream.flush();
	        outputStream.close();

	        StringBuffer stringBuffer=new StringBuffer();
	        BufferedReader bufferedReader=null;
	        String result=null;
	        try {
	            bufferedReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String line=null;
	            while ((line=bufferedReader.readLine())!=null){
	                    stringBuffer.append(line);
	            }
	            if (result==null){
	                result=stringBuffer.toString();
	            }
	        }catch (IOException e){
	            e.printStackTrace();
	        }finally {
	            if (bufferedReader!=null){
	                bufferedReader.close();
	            }
	        }

	        JSONObject jsonObject= JSON.parseObject(result);
	        String typeName="media_id";
	        if (!"image".equals(type)){
	            typeName=type+"_media_id";
	        }
	        String media_id= (String) jsonObject.get(typeName);
	        System.out.println(media_id);
	        return media_id;
	    }

接下来写个测试方法测试一次。

 public static void main(String[] args) throws IOException {

	        String path="D:\\timg.jpg";
	        File  file = new File(path);
	        if(file == null){
	        	System.out.println("null");
	        }else{
	        	System.out.println(123);
	        }
	        String acctoken="填写自己的acctoken";
	        String media_id=upload(acctoken,path,"image");
	    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值