httpmime实现http请求—post以及get请求、文件下载等

摘要

非web项目实现文件下载,使用apache的httpmime工具进行相关的http请求操做。java

正题

需求:实现非web项目进行文件下载或者http请求。web

一、添加相关pom依赖apache

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.5</version>
</dependency>

二、请求相关工具代码json

package com.lanxuewei.utils.file.deepwise;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.lanxuewei.utils.io.IOUtils;

/** * @author lanxuewei Create in 2018/9/19 16:54 * Description: 本地http请求帮助类 */
public class HttpClientHelper {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

    /** * http post请求,json格式传输参数 * * @param map 参数对 * @param url url地址 * @return * @throws IOException */
    public String postWithHttp(Map<String, Object> map, String url) {
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000).build();
        httpPost.setConfig(requestConfig);
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");

        httpPost.setEntity(stringEntity);

        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                return EntityUtils.toString(resEntity);
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        return "";
    }

    /** * 表单提交 post请求 * * @param map 参数对 * @param url url * @param token token * @return 响应流 * @throws IOException */
    public String postFormWithHttp(Map<String, Object> map, String url, String token) {
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000).build();
        httpPost.setConfig(requestConfig);
        
        httpPost.setHeader("token", token);
        ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), contentType));
        }
        HttpEntity httpEntity = null;
        try {
            httpEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }
        httpPost.setEntity(httpEntity);

        return execute(client, httpPost);
    }

    /** * get请求 * * @param map 参数对 * @param url url * @param token token * @return 响应流 * @throws IOException */
    public String getWithHttp(Map<String, Object> map, String url, String token) {
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("token", token);
        return execute(client, httpGet);
    }

    /** * 执行请求并响应 * * @param client client * @param httpPost httpPost * @return 结果流字符串 */
    private String execute(CloseableHttpClient client, HttpRequestBase httpPost) {
        if (client == null || httpPost == null) {
            return "";
        }
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                return EntityUtils.toString(resEntity);
            }
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            IOUtils.safeClose(response);
        }
        return "";
    }

    /** * 文件下载 * * @param url url * @param token token * @return 响应流 * @throws IOException */
    public boolean downFileByGet(String url, String token, File targetFile) {
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000).build();
        httpGet.setConfig(requestConfig);

        httpGet.setHeader("token", token);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            logger.error("", e);
        }
        assert response != null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            try {
                // org.apache.commons.io.IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(targetFile));
                response.getEntity().writeTo(new FileOutputStream(targetFile)); // 写入文件
            } catch (IOException e) {
                logger.error("", e);
            }
        }
        return true;
    }
}

说明:
一、本代码中采用的是日志是logback,json相关解析等采用的是fastjson,直接拷贝代码会有错误,因此须要引入相关依赖,因为和本文章内容关系不大,因此前排依赖中没有给出,本文最后会给出,或者不采用日志以及采用别的也行
二、有些请求函数中包含token,这是由于笔者的需求须要token认证,因此去掉或者保留看读者须要
三、url为完整的接口访问路径,例:http://localhost:8080/index
四、请求中的参数采用map传入,即 参数名-参数值 键值对
五、最后一个函数downFileByGet为文件下载函数api

三、 logback相关依赖app

<!-- httpmine -->
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.1.11</version>
</dependency>
<!-- fastJson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.39</version>
</dependency>

补充:以前因为没有手动设置超时时间,因此若是请求长时间无响应的话会致使一直等待阻塞问题出现,因此补充超时设置代码,以上代码已补充,下面也贴出手动设置超时代码块,代码以下:svg

// 设置超时时间
 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
         .setConnectionRequestTimeout(5000)
         .setSocketTimeout(5000).build();
 httpPost.setConfig(requestConfig);