国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

使用HttpClient實(shí)現(xiàn)文件的上傳下載方法

2019-11-26 13:25:51
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1 HTTP

HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了,越來(lái)越多的 Java 應(yīng)用程序需要直接通過(guò) HTTP 協(xié)議來(lái)訪問(wèn)網(wǎng)絡(luò)資源。

雖然在 JDK 的 java.net 包中已經(jīng)提供了訪問(wèn) HTTP 協(xié)議的基本功能,但是對(duì)于大部分應(yīng)用程序來(lái)說(shuō),JDK 庫(kù)本身提供的功能還不夠豐富和靈活。HttpClient 用來(lái)提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶(hù)端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。

一般的情況下我們都是使用Chrome或者其他瀏覽器來(lái)訪問(wèn)一個(gè)WEB服務(wù)器,用來(lái)瀏覽頁(yè)面查看信息或者提交一些數(shù)據(jù)、文件上傳下載等等。所訪問(wèn)的這些頁(yè)面有的僅僅是一些普通的頁(yè)面,有的需要用戶(hù)登錄后方可使用,或者需要認(rèn)證以及是一些通過(guò)加密方式傳輸,例如HTTPS。目前我們使用的瀏覽器處理這些情況都不會(huì)構(gòu)成問(wèn)題。但是一旦我們有需求不通過(guò)瀏覽器來(lái)訪問(wèn)服務(wù)器的資源呢?那該怎么辦呢?

下面以本地客戶(hù)端發(fā)起文件的上傳、下載為例做個(gè)小Demo。HttpClient有兩種形式,一種是org.apache.http下的,一種是org.apache.commons.httpclient.HttpClient。

2 文件上傳

文件上傳可以使用兩種方式實(shí)現(xiàn),一種是PostMethod方式,一種是HttpPost方式。兩者的處理大同小異。PostMethod是使用FileBody將文件包裝流包裝起來(lái),HttpPost是使用FilePart將文件流包裝起來(lái)。在傳遞文件流給服務(wù)端的時(shí)候,都可以同時(shí)傳遞其他的參數(shù)。

2.1 客戶(hù)端處理

2.1.1 PostMethod方式

將文件封裝到FilePart中,放入Part數(shù)組,同時(shí),其他參數(shù)可以放入StringPart中,這里沒(méi)有寫(xiě),只是單純的將參數(shù)以setParameter的方式進(jìn)行設(shè)置。此處的HttpClient是org.apache.commons.httpclient.HttpClient。

 

public void upload(String localFile){    File file = new File(localFile);    PostMethod filePost = new PostMethod(URL_STR);    HttpClient client = new HttpClient();        try {      // 通過(guò)以下方法可以模擬頁(yè)面參數(shù)提交      filePost.setParameter("userName", userName);      filePost.setParameter("passwd", passwd);      Part[] parts = { new FilePart(file.getName(), file) };      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);            int status = client.executeMethod(filePost);      if (status == HttpStatus.SC_OK) {        System.out.println("上傳成功");      } else {        System.out.println("上傳失敗");      }    } catch (Exception ex) {      ex.printStackTrace();    } finally {      filePost.releaseConnection();    }  }

記得搞完之后,要通過(guò)releaseConnection釋放連接。

2.1.2 HttpPost方式

這種方式,與上面類(lèi)似,只不過(guò)變成了FileBody。上面的Part數(shù)組在這里對(duì)應(yīng)HttpEntity。此處的HttpClient是org.apache.http.client.methods下的。

public void upload(String localFile){    CloseableHttpClient httpClient = null;    CloseableHttpResponse response = null;    try {      httpClient = HttpClients.createDefault();            // 把一個(gè)普通參數(shù)和文件上傳給下面這個(gè)地址 是一個(gè)servlet      HttpPost httpPost = new HttpPost(URL_STR);            // 把文件轉(zhuǎn)換成流對(duì)象FileBody      FileBody bin = new FileBody(new File(localFile));      StringBody userName = new StringBody("Scott", ContentType.create(          "text/plain", Consts.UTF_8));      StringBody password = new StringBody("123456", ContentType.create(          "text/plain", Consts.UTF_8));      HttpEntity reqEntity = MultipartEntityBuilder.create()          // 相當(dāng)于<input type="file" name="file"/>          .addPart("file", bin)                    // 相當(dāng)于<input type="text" name="userName" value=userName>          .addPart("userName", userName)          .addPart("pass", password)          .build();      httpPost.setEntity(reqEntity);      // 發(fā)起請(qǐng)求 并返回請(qǐng)求的響應(yīng)      response = httpClient.execute(httpPost);            System.out.println("The response value of token:" + response.getFirstHeader("token"));              // 獲取響應(yīng)對(duì)象      HttpEntity resEntity = response.getEntity();      if (resEntity != null) {        // 打印響應(yīng)長(zhǎng)度        System.out.println("Response content length: " + resEntity.getContentLength());        // 打印響應(yīng)內(nèi)容        System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));      }            // 銷(xiāo)毀      EntityUtils.consume(resEntity);    }catch (Exception e){      e.printStackTrace();    }finally {      try {        if(response != null){          response.close();        }      } catch (IOException e) {        e.printStackTrace();      }            try {        if(httpClient != null){          httpClient.close();        }      } catch (IOException e) {        e.printStackTrace();      }    }  }

2.2 服務(wù)端處理

 無(wú)論客戶(hù)端是哪種上傳方式,服務(wù)端的處理都是一樣的。在通過(guò)HttpServletRequest獲得參數(shù)之后,把得到的Item進(jìn)行分類(lèi),分為普通的表單和File表單。

 通過(guò)ServletFileUpload 可以設(shè)置上傳文件的大小及編碼格式等。

 總之,服務(wù)端的處理是把得到的參數(shù)當(dāng)做HTML表單進(jìn)行處理的。  

public void processUpload(HttpServletRequest request, HttpServletResponse response){    File uploadFile = new File(uploadPath);    if (!uploadFile.exists()) {      uploadFile.mkdirs();    }    System.out.println("Come on, baby .......");        request.setCharacterEncoding("utf-8");     response.setCharacterEncoding("utf-8");          //檢測(cè)是不是存在上傳文件     boolean isMultipart = ServletFileUpload.isMultipartContent(request);          if(isMultipart){       DiskFileItemFactory factory = new DiskFileItemFactory();             //指定在內(nèi)存中緩存數(shù)據(jù)大小,單位為byte,這里設(shè)為1Mb       factory.setSizeThreshold(1024*1024);             //設(shè)置一旦文件大小超過(guò)getSizeThreshold()的值時(shí)數(shù)據(jù)存放在硬盤(pán)的目錄        factory.setRepository(new File("D://temp"));             // Create a new file upload handler       ServletFileUpload upload = new ServletFileUpload(factory);             // 指定單個(gè)上傳文件的最大尺寸,單位:字節(jié),這里設(shè)為50Mb        upload.setFileSizeMax(50 * 1024 * 1024);              //指定一次上傳多個(gè)文件的總尺寸,單位:字節(jié),這里設(shè)為50Mb       upload.setSizeMax(50 * 1024 * 1024);         upload.setHeaderEncoding("UTF-8");             List<FileItem> items = null;              try {         // 解析request請(qǐng)求         items = upload.parseRequest(request);       } catch (FileUploadException e) {         e.printStackTrace();       }             if(items!=null){         //解析表單項(xiàng)目         Iterator<FileItem> iter = items.iterator();         while (iter.hasNext()) {           FileItem item = iter.next();                     //如果是普通表單屬性           if (item.isFormField()) {             //相當(dāng)于input的name屬性  <input type="text" name="content">             String name = item.getFieldName();                        //input的value屬性             String value = item.getString();                        System.out.println("屬性:" + name + " 屬性值:" + value);           }           //如果是上傳文件           else {             //屬性名             String fieldName = item.getFieldName();                         //上傳文件路徑             String fileName = item.getName();             fileName = fileName.substring(fileName.lastIndexOf("/") + 1);// 獲得上傳文件的文件名                         try {               item.write(new File(uploadPath, fileName));             } catch (Exception e) {               e.printStackTrace();             }           }         }       }     }         response.addHeader("token", "hello");  }

服務(wù)端在處理之后,可以在Header中設(shè)置返回給客戶(hù)端的簡(jiǎn)單信息。如果返回客戶(hù)端是一個(gè)流的話,流的大小必須提前設(shè)置!

response.setContentLength((int) file.length());

3 文件下載

文件的下載可以使用HttpClient的GetMethod實(shí)現(xiàn),還可以使用HttpGet方式、原始的HttpURLConnection方式。

3.1 客戶(hù)端處理

3.1.1 GetMethod方式

此處的HttpClient是org.apache.commons.httpclient.HttpClient。

public void downLoad(String remoteFileName, String localFileName) {    HttpClient client = new HttpClient();    GetMethod get = null;    FileOutputStream output = null;        try {      get = new GetMethod(URL_STR);      get.setRequestHeader("userName", userName);      get.setRequestHeader("passwd", passwd);      get.setRequestHeader("fileName", remoteFileName);      int i = client.executeMethod(get);      if (SUCCESS == i) {        System.out.println("The response value of token:" + get.getResponseHeader("token"));        File storeFile = new File(localFileName);        output = new FileOutputStream(storeFile);                // 得到網(wǎng)絡(luò)資源的字節(jié)數(shù)組,并寫(xiě)入文件        output.write(get.getResponseBody());      } else {        System.out.println("DownLoad file occurs exception, the error code is :" + i);      }    } catch (Exception e) {      e.printStackTrace();    } finally {      try {        if(output != null){          output.close();        }      } catch (IOException e) {        e.printStackTrace();      }            get.releaseConnection();      client.getHttpConnectionManager().closeIdleConnections(0);    }  }

3.1.2 HttpGet方式

此處的HttpClient是org.apache.http.client.methods下的。

public void downLoad(String remoteFileName, String localFileName) {    DefaultHttpClient httpClient = new DefaultHttpClient();    OutputStream out = null;    InputStream in = null;        try {      HttpGet httpGet = new HttpGet(URL_STR);      httpGet.addHeader("userName", userName);      httpGet.addHeader("passwd", passwd);      httpGet.addHeader("fileName", remoteFileName);      HttpResponse httpResponse = httpClient.execute(httpGet);      HttpEntity entity = httpResponse.getEntity();      in = entity.getContent();      long length = entity.getContentLength();      if (length <= 0) {        System.out.println("下載文件不存在!");        return;      }      System.out.println("The response value of token:" + httpResponse.getFirstHeader("token"));      File file = new File(localFileName);      if(!file.exists()){        file.createNewFile();      }            out = new FileOutputStream(file);       byte[] buffer = new byte[4096];      int readLength = 0;      while ((readLength=in.read(buffer)) > 0) {        byte[] bytes = new byte[readLength];        System.arraycopy(buffer, 0, bytes, 0, readLength);        out.write(bytes);      }            out.flush();          } catch (IOException e) {      e.printStackTrace();    } catch (Exception e) {      e.printStackTrace();    }finally{      try {        if(in != null){          in.close();        }      } catch (IOException e) {        e.printStackTrace();      }            try {        if(out != null){          out.close();        }      } catch (IOException e) {        e.printStackTrace();      }    }  }

3.1.3 HttpURLConnection方式

public void download3(String remoteFileName, String localFileName) {    FileOutputStream out = null;    InputStream in = null;        try{      URL url = new URL(URL_STR);      URLConnection urlConnection = url.openConnection();      HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;            // true -- will setting parameters      httpURLConnection.setDoOutput(true);      // true--will allow read in from      httpURLConnection.setDoInput(true);      // will not use caches      httpURLConnection.setUseCaches(false);      // setting serialized      httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");      // default is GET                  httpURLConnection.setRequestMethod("POST");      httpURLConnection.setRequestProperty("connection", "Keep-Alive");      httpURLConnection.setRequestProperty("Charsert", "UTF-8");      // 1 min      httpURLConnection.setConnectTimeout(60000);      // 1 min      httpURLConnection.setReadTimeout(60000);      httpURLConnection.addRequestProperty("userName", userName);      httpURLConnection.addRequestProperty("passwd", passwd);      httpURLConnection.addRequestProperty("fileName", remoteFileName);      // connect to server (tcp)      httpURLConnection.connect();      in = httpURLConnection.getInputStream();// send request to                                // server      File file = new File(localFileName);      if(!file.exists()){        file.createNewFile();      }      out = new FileOutputStream(file);       byte[] buffer = new byte[4096];      int readLength = 0;      while ((readLength=in.read(buffer)) > 0) {        byte[] bytes = new byte[readLength];        System.arraycopy(buffer, 0, bytes, 0, readLength);        out.write(bytes);      }            out.flush();    }catch(Exception e){      e.printStackTrace();    }finally{      try {        if(in != null){          in.close();        }      } catch (IOException e) {        e.printStackTrace();      }            try {        if(out != null){          out.close();        }      } catch (IOException e) {        e.printStackTrace();      }    }  }

3.2 服務(wù)端處理

盡管客戶(hù)端的處理方式不同,但是服務(wù)端是一樣的。

public void processDownload(HttpServletRequest request, HttpServletResponse response){    int BUFFER_SIZE = 4096;    InputStream in = null;    OutputStream out = null;        System.out.println("Come on, baby .......");        try{      request.setCharacterEncoding("utf-8");       response.setCharacterEncoding("utf-8");       response.setContentType("application/octet-stream");            String userName = request.getHeader("userName");      String passwd = request.getHeader("passwd");      String fileName = request.getHeader("fileName");            System.out.println("userName:" + userName);      System.out.println("passwd:" + passwd);      System.out.println("fileName:" + fileName);            //可以根據(jù)傳遞來(lái)的userName和passwd做進(jìn)一步處理,比如驗(yàn)證請(qǐng)求是否合法等             File file = new File(downloadPath + "http://" + fileName);      response.setContentLength((int) file.length());      response.setHeader("Accept-Ranges", "bytes");            int readLength = 0;            in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);      out = new BufferedOutputStream(response.getOutputStream());            byte[] buffer = new byte[BUFFER_SIZE];      while ((readLength=in.read(buffer)) > 0) {        byte[] bytes = new byte[readLength];        System.arraycopy(buffer, 0, bytes, 0, readLength);        out.write(bytes);      }            out.flush();            response.addHeader("token", "hello 1");           }catch(Exception e){      e.printStackTrace();       response.addHeader("token", "hello 2");    }finally {      if (in != null) {        try {          in.close();        } catch (IOException e) {        }      }      if (out != null) {        try {          out.close();        } catch (IOException e) {        }      }    }  }

4 小結(jié)

HttpClient最基本的功能就是執(zhí)行Http方法。一個(gè)Http方法的執(zhí)行涉及到一個(gè)或者多個(gè)Http請(qǐng)求/Http響應(yīng)的交互,通常這個(gè)過(guò)程都會(huì)自動(dòng)被HttpClient處理,對(duì)用戶(hù)透明。用戶(hù)只需要提供Http請(qǐng)求對(duì)象,HttpClient就會(huì)將http請(qǐng)求發(fā)送給目標(biāo)服務(wù)器,并且接收服務(wù)器的響應(yīng),如果http請(qǐng)求執(zhí)行不成功,httpclient就會(huì)拋出異常。所以在寫(xiě)代碼的時(shí)候注意finally的處理。

所有的Http請(qǐng)求都有一個(gè)請(qǐng)求列(request line),包括方法名、請(qǐng)求的URI和Http版本號(hào)。HttpClient支持HTTP/1.1這個(gè)版本定義的所有Http方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS。上面的上傳用到了Post,下載是Get。

目前來(lái)說(shuō),使用org.apache.commons.httpclient.HttpClient多一些。看自己了~

以上就是小編為大家?guī)?lái)的使用HttpClient實(shí)現(xiàn)文件的上傳下載方法全部?jī)?nèi)容了,希望大家多多支持武林網(wǎng)~

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 隆德县| 张家港市| 阿克苏市| 云浮市| 西城区| 延庆县| 墨玉县| 贵溪市| 大厂| 长兴县| 南充市| 通辽市| 县级市| 招远市| 湖南省| 龙州县| 蓝山县| 贵溪市| 庆城县| 衡南县| 无棣县| 成安县| 广汉市| 松阳县| 买车| 马龙县| 紫金县| 板桥市| 额尔古纳市| 金湖县| 白朗县| 襄垣县| 手游| 巩留县| 凤山市| 郴州市| 乡城县| 佳木斯市| 廊坊市| 新疆| 南充市|