java - 使用 Java 通过 http 上传文件时获取上传速度百分比进度?

标签 java performance file-upload upload

我正在编写一些代码来在 http url 上上传文件。但我不知道如何在传输时获取 %age 和上传速度以使其更加详细。

httpupload.java

   import java.io.File;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.RandomAccessFile;
   import java.io.StringWriter;
   import java.io.UnsupportedEncodingException;
   import java.text.DecimalFormat;

   import javax.xml.ws.spi.http.HttpContext;

   import org.apache.http.HttpEntity;
   import org.apache.http.HttpResponse;
   import org.apache.http.HttpVersion;
   import org.apache.http.client.HttpClient;
   import org.apache.http.client.methods.HttpPost;
   import org.apache.http.client.methods.HttpPut;
   import org.apache.http.entity.mime.MultipartEntity;
   import org.apache.http.entity.mime.content.FileBody;
   import org.apache.http.impl.client.DefaultHttpClient;
   import org.apache.http.params.BasicHttpParams;
   import org.apache.http.params.HttpParams;
   import org.apache.http.params.HttpProtocolParams;
   import org.apache.http.protocol.BasicHttpContext;

   public class httpupload  {
String str;
private int transferedMegaBytes = 0;
int choice;
long size = 0;
static int iter;
DecimalFormat df = new DecimalFormat("#.00");
RandomAccessFile f1;
httpUploadProgress fileEntity;

boolean bo1, bo2, bo3, bo4;// truefalsetruefalse

public httpupload(boolean b1, boolean b2, boolean b3, boolean b4,
        int Iterations) {
    super();

    // TODO Auto-generated constructor stub
    bo1 = b1;
    bo2 = b2;
    bo3 = b3;
    bo4 = b4;
    this.iter = Iterations;
    if(bo1){
        ProgressBar.maxprogress+= iter*250*1024;
    }
    if(bo2){
        ProgressBar.maxprogress+=iter*500*1024;
    }
    if(bo3){
        ProgressBar.maxprogress+=iter*2*1024*1024;
    }
    if(bo4){
        ProgressBar.maxprogress+=iter*10*1024*1024;
    }

    try {
        ProgressBar.status="Uploading File via HTTP";
        this.chooseFiles(bo1, bo2, bo3, bo4);
        //System.out.println(httpUploadProgress.getSpeed());
    } catch (Exception ex) {
        //System.out.println(ex.getLocalizedMessage());
    }   
}

public void chooseFiles(boolean b1, boolean b2, boolean b3, boolean b4)
        throws Exception {
    for (int i = 0; i < iter; i++) {
        if (b1) {
            ProgressBar.status="Uploading File Of Size 250KB";
            this.startUpload(1);
        }
        if (b2) {
            ProgressBar.status="Uploading File Of Size 500KB";
            this.startUpload(2);
        }
        if (b3) {
            ProgressBar.status="Uploading File Of Size 2MB";
            this.startUpload(3);
        }
        if (b4) {
            ProgressBar.status="Uploading File Of Size 10MB";
            //this.post();
            this.startUpload(4);
        }
    }
    httpUploadProgress.totalSpeed /= iter;
}

public static void main(String args[]) {
    httpupload av = new httpupload(false, false, false, true, 2);

}

private void startUpload(int choice) throws Exception {
    String str = "";
    switch (choice) {
    case 1:
        str = "250kb.txt";
        size = 250 * 1024;
        break;
    case 2:
        str = "500kb.txt";
        size = 500 * 1024;
        break;
    case 3:
        str = "2MB.txt";
        size = 2 * 1024 * 1024;
        break;
    case 4:
        str = "10MB.txt";
        size = 10 * 1024 * 1024;
        break;
    }

    //str="/sdcard/"+str;
    f1 = new RandomAccessFile(str, "rw");
    f1.setLength(size);
    File file = new File(str);

    String serverResponse = null;
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    HttpPut put = new HttpPut("URL"
            + file.getName());
    //HttpPost httpPost = new HttpPost("URL");

    fileEntity = new httpUploadProgress(file, "binary/octet-stream");
    put.setEntity(fileEntity);
    //httpPost.setEntity(fileEntity);
    HttpResponse response = client.execute(put);
    //HttpResponse response = client.execute(httpPost);

    // HttpEntity entity = response.getEntity();
    /*
     * if (entity != null) { serverResponse = EntityUtils.toString(entity);
     * //System.out.println(serverResponse); }
     */

    File f2 = new File(str);
    f2.delete();

}

httpuploadProgress.java

        import java.io.File;
         import java.io.FileInputStream;
         import java.io.IOException;
         import java.io.InputStream;
         import java.io.OutputStream;
         import java.text.DecimalFormat;

         import org.apache.http.entity.AbstractHttpEntity;

        /**
        * File entity which supports a progress bar.<br/>
        * Based on "org.apache.http.entity.FileEntity".
        * @author Benny Neugebauer (www.bennyn.de)
        */
        public class httpUploadProgress extends AbstractHttpEntity implements Cloneable
        {

  protected final File file;
 // private final ProgressBarListener listener;
  private long transferredBytes;
  private long transferedMegaBytes = 0;
  long startTime, endTime,totalTime;
  static double speed,totalSpeed;
  static DecimalFormat df = new DecimalFormat("#.00");
  int choice;
  static String metrics;

  public httpUploadProgress(final File file, final String contentType)
  {
    super();
    if (file == null)
    {
      throw new IllegalArgumentException("File may not be null");
    }
    this.file = file;
    this.transferredBytes = 0;
    setContentType(contentType);
  }

  public boolean isRepeatable()
  {
    return true;
  }

  public long getContentLength()
  {
    return this.file.length();
  }

  public InputStream getContent() throws IOException
  {
    return new FileInputStream(this.file);
  }

  public void writeTo(final OutputStream outstream) throws IOException
  {
    if (outstream == null)
    {
      throw new IllegalArgumentException("Output stream may not be null");
    }
    InputStream instream = new FileInputStream(this.file);
    try
    {

        {
        byte[] tmp = new byte[1024];
      int l;
       startTime = System.nanoTime();

      while ((l = instream.read(tmp)) != -1)
      {
        outstream.write(tmp, 0, l);
        this.transferredBytes += l;

        updateTransferred(this.transferredBytes);
      }
      outstream.flush();
      endTime = System.nanoTime();
        System.out.println("End Time of "+"is :"+endTime);
        totalTime = (endTime - startTime)/1000000000;
        speed=(double)(transferredBytes/totalTime);
        System.out.println("Bytes is :"+transferredBytes);
        totalSpeed+=speed;
        System.out.println("Speed is :"+totalSpeed);
        }

    }
    finally
    {
      instream.close();
    }
  }


  public void updateTransferred(long transferedBytes)
  {
    transferedMegaBytes =  (transferedBytes/(1024*1024) );
    ProgressBar.status="Uploading File";
    System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
  ProgressBar.progress+=(int)transferedBytes;
  }


  public String getResult(int i) throws NumberFormatException, IOException{

        choice=i;
        switch(choice)
        {
            case 1://System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 2:httpUploadProgress.totalSpeed/=1024;
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 3:httpUploadProgress.totalSpeed/=(1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 4:httpUploadProgress.totalSpeed/=(1024*1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
        }

        return df.format(httpUploadProgress.totalSpeed);
  }
  public static String getSpeedbps(){

      return    df.format(totalSpeed);
      }

  public static String getSpeedkbps(){
      return df.format(totalSpeed/=1024);

  }
      public static String getSpeedmbps(){

      return    df.format(totalSpeed/=(1024*1024));
      }
      public static String getSpeedgbps(){

      return    df.format(totalSpeed/=(1024*1024*1024));
      }

  public boolean isStreaming()
  {
    return false;
  }
  public static String getSpeed(){
    String str2 = "";
    if((totalSpeed<=1024)){
        str2=""+getSpeedbps();
        metrics=" Bps";
    }else if((totalSpeed>=1024)&& ((totalSpeed<(1024*1024 )))){

        str2=""+getSpeedkbps();
        metrics=" KBps";
    }else if((totalSpeed>=1024*1024)&& ((totalSpeed<(1024*1024*1024 )))){

        str2=""+getSpeedmbps();
        metrics=" MBps";
    }else if((totalSpeed>=1024*1024*1024 )){

        str2=""+getSpeedgbps();
        metrics=" GBps";
    }
    return str2;
  }

  public static String showSpeed(){
        String temp=""+getSpeed()+" "+getMetrics();
        return temp;
    }

    public static String getMetrics(){
        return metrics;
    }
  @Override
  public Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }
}

一些代码也被弃用。我不知道如何使用最新的 apache httpclient 上传文件?我正在做我的研究项目,所以请求帮助解决这个问题。我是 JAVA 新手。

谢谢

最佳答案

似乎这个问题已经有答案了 file-upload-with-java-with-progress-bar

主要是 HttpClient 在某处使用输出流将数据发送到目标。您必须包装此输出流以计算已发送/处理的字节数。

还可以通过 file.size() 了解完整的文件大小,您应该能够显示百分比。

在第二个线程的帮助下,您可以监视耗时并确定字节/秒。

关于java - 使用 Java 通过 http 上传文件时获取上传速度百分比进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459248/

相关文章:

C# 将文件保存到服务器上的文件夹而不是本地

java - Swing JTable 布局 : how to make table occupy complete viewport - like in eclipse IDE

java - 管理版本

performance - Python,迭代正则表达式但在第一次匹配时停止的最快方法

sql - 使用 'IN' 运算符组合两个查询时如何提高性能

SQL Server - 与 NULL 相比非常慢

java - 从 JSON 模式生成示例 JSON 数据

java - 从父类公共(public)成员调用子类私有(private)成员

php - 正确的文件上传文件夹权限

php - 上传大文件时连接中止