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

摘要

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

正题

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

1、添加相关pom依赖


	org.apache.httpcomponents
	httpmime
	4.5.5

2、请求相关工具代码

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;
    }
}

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

3、 logback相关依赖



	ch.qos.logback
	logback-classic
	1.1.11



	com.alibaba
	fastjson
	1.2.39


补充:之前由于没有手动设置超时时间,所以如果请求长时间无响应的话会导致一直等待阻塞问题出现,所以补充超时设置代码,以上代码已补充,下面也贴出手动设置超时代码块,代码如下:

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

你可能感兴趣的:(Java,文件相关,http请求,httpmime)