通过http协议取得网络文件并进行base64编码

public String Read() {
    try {
      URL url = new URL(urlfile);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      DataInputStream in = new DataInputStream(connection.getInputStream());
      // BufferedReader in = new BufferedReader(new InputStreamReader(connection.
      //    getInputStream()));
      //DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));

      byte[] a = new byte[20000];
      byte[] b = new byte[20000];
      int count1 = 0;
      int count2 = 0;
      int total = 0;
      int i = 0;
      String sCurrentLine = "";
      String sTotalLine = "";

      if ( (count1 = in.read(a)) != -1) {
        System.out.println(count1);

      }
      if ( (count2 = in.read(b)) != -1) {
        System.out.println(count2);

      }
      byte[] buffer = new byte[count1 + count2];
      for (i = 0; i < count1; i++) {
        buffer[i] = a[i];
      }
      for (i = 0; i < count2; i++) {
        buffer[count1 + i] = b[i];
      }
      sun.misc.BASE64Encoder encode = new sun.misc.BASE64Encoder();
      base64str = encode.encode(buffer);
      // encode.encode(in,out);

      //out.close();
      in.close();
      //return true;
    }
    catch (Exception e) {
      System.out.println(e.toString());
    }

    return base64str;

  }

在实际工作中,发现以上方法不能一次取得url文件的所有内容,于是又写了以下一个方法

 public String Read() {
    DataInputStream in = null;
    try {
      URL url = new URL(urlfile);
      HttpURLConnection connection = (HttpURLConnection) url.
          openConnection();
      in = new DataInputStream(connection.getInputStream());
    }
    catch (IOException eIo) {}
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bo);
    sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    try {
      encoder.encode(in, out);
    }
    catch (IOException eIo) {}
    return new String(bo.toByteArray());

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值