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文件创建失败");
                }
            }

猜你喜欢

转载自blog.csdn.net/zhaoxichen_10/article/details/84872005