1. 程式人生 > >httpClient上傳下載檔案

httpClient上傳下載檔案

HTTP 協議可能是現在 Internet 上使用得最多、最重要的協議了,越來越多的 Java 應用程式需要直接通過 HTTP 協議來訪問網路資源。雖然在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能,但是對於大部分應用程式來說,JDK 庫本身提供的功能還不夠豐富和靈活。HttpClient 是 Apache Jakarta Common 下的子專案,用來提供高效的、最新的、功能豐富的支援 HTTP 協議的客戶端程式設計工具包,並且它支援 HTTP 協議最新的版本和建議。HttpClient 已經應用在很多的專案中。
使用HttpClient傳送請求、接收響應很簡單,一般需要如下幾步即可。

  1. 建立HttpClient物件。
  2. 建立請求方法的例項,並指定請求URL。如果需要傳送GET請求,建立HttpGet物件;如果需要傳送POST請求,建立HttpPost物件。
  3. 如果需要傳送請求引數,可呼叫HttpGet、HttpPost共同的setParams(HetpParams params)方法來新增請求引數;對於HttpPost物件而言,也可呼叫setEntity(HttpEntity entity)方法來設定請求引數。
  4. 呼叫HttpClient物件的execute(HttpUriRequest request)傳送請求,該方法返回一個HttpResponse。
  5. 呼叫HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取伺服器的響應頭;呼叫HttpResponse的getEntity()方法可獲取HttpEntity物件,該物件包裝了伺服器的響應內容。程式可通過該物件獲取伺服器的響應內容。
  6. 釋放連線。無論執行方法是否成功,都必須釋放連線

上面都是一些百科,是我抄襲不知道是哪個網友的。關於httpclient的理論,如果還有不清楚的可以自行百度或者Google查閱;
下面是乾貨:
我的使用方式是封裝成了一個工具類
1、pom.xml依賴

	  <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

2、封裝成工具類

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    /**
    * 此處省略了許多其他的工具方法,只展示本文相關的
    **/
    /**
 * TODO: PostMethod方式上傳檔案
 *
 * @return
 * @throws
 * @author zhaoxi
 * @time 2018/12/7 10:44
 * @params
 */
public boolean uploadFile(String remoteUrl, String localFile) {
        File file = new File(localFile);
        if (!file.exists()) {
            return false;
        }
        PostMethod filePost = new PostMethod(remoteUrl);
        HttpClient client = new HttpClient();
        boolean result = false;
        try {
            // 如果目標伺服器還需要其他引數,通過以下方法可以模擬頁面引數提交,
            //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);//設定超時時間為5秒
            int status = client.executeMethod(filePost);
            if (200 == status) {
                result = true;
                System.out.println("上傳成功");
            } else {
                System.out.println("上傳失敗");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            filePost.releaseConnection();
        }
        return result;
    }

/**
 * TODO: GetMethod方式下載檔案
 *
 * @return
 * @throws
 * @author zhaoxi
 * @time 2018/12/7 10:14
 * @params
 */
public static boolean downloadFile(String remoteUrl, String remoteFileName, String localPath, String localFileName) {
        boolean result = false;
        HttpClient client = new HttpClient();
        GetMethod get = null;
        FileOutputStream output = null;
        try {
            get = new GetMethod(remoteUrl);
            // 通過以下方法可以模擬頁面引數提交,
            //get.setRequestHeader("userName", userName);
            //get.setRequestHeader("passwd", passwd);
            get.setRequestHeader("fileName", remoteFileName);
            int status = client.executeMethod(get);

            if (200 == status) {
                /**
                 * 建立本地檔案,接收下載的資源
                 */
                File storeFile;
                if (Util.isEmpty(localFileName)) {
                    localFileName = remoteFileName; //檔案命名不變
                }
                if (Util.isEmpty(localPath)) {
                    storeFile = new File(localFileName);
                } else {
                    storeFile = new File(localPath + "/" + localFileName);
                }
                output = new FileOutputStream(storeFile);
                // 得到網路資源的位元組陣列,並寫入檔案
                output.write(get.getResponseBody());
                result = true;
            } else {
                System.out.println("DownLoad file occurs exception, the error code is :" + status);
            }
        	} catch (Exception e) {
           		 e.printStackTrace();
       	       } finally {
	            try {
	                if (output != null) {
	                    output.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
              }

            get.releaseConnection();
            client.getHttpConnectionManager().closeIdleConnections(0);
        }
        return result;
    }

    public static boolean downloadFile(String remoteUrl, String remoteFileName, String localPath) {
        return downloadFile(remoteUrl, remoteFileName, localPath, null);
    }

    public static boolean downloadFile(String remoteUrl, String remoteFileName) {
        return downloadFile(remoteUrl, remoteFileName, null, null);
    }

}

3、呼叫

 		 File avatarImg = new File("logo/code_logo.png");
            if (!avatarImg.exists()) {
                log.info("檔案不存在,正在下載...");
                String logoDirPath = "logo";
                /**
                 * 檢查資料夾是否存在
                 */
                File logoDir = new File(logoDirPath);
                if (!logoDir.exists()) {
                    logoDir.mkdir();
                }
                /**
                 * 從圖片伺服器下載logo檔案
                 */
                boolean isDownSuccess = HttpUtil.downloadFile(CODE_LOGO_URL, "code_logo.png", logoDirPath);
                if (!isDownSuccess) {
                    return PaixiResult.build(501, "logo檔案下載失敗");
                }
                /**
                 * 再次判斷檔案是否存在
                 */
                if (!avatarImg.exists()) {
                    return PaixiResult.build(501, "logo檔案建立失敗");
                }
            }