Httpclient发送Post、Get请求、文件上传下载

Httpclient

引入maven依赖

<!-- httpclient依赖 -->
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.13</version>
</dependency>

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.75</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.16</version>
   <scope>provided</scope>
</dependency>

<!-- httpcomponents -->
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpmime</artifactId>
   <version>4.5.13</version>
</dependency>

提取发送请求方法


/**
 * 发送请求
 * @param request 请求 HttpPost/HttpGet
 * @return string
 * @throws IOException
 */
private static String request(HttpUriRequest request) {
    String result = null;
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
         CloseableHttpResponse response = httpClient.execute(request)
        ){
        log.info("响应状态:" + response.getStatusLine());
        HttpEntity httpEntity = response.getEntity();
        if(httpEntity != null){
            result = EntityUtils.toString(httpEntity, Charset.forName("utf-8"));
            log.info("响应内容:" + result);
        }
    }catch (Exception e){
        log.error("发送请求错误",e);
    }
    return result;
}

普通Get请求

/**
 * get请求
 * @param url url,参数拼接在后面 ?name=val&name1=var1
 * @return
 */
public static String doGet(String url){
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(DEFAULT_CONFIG);
    return request(httpGet);
}

带头信息的Get请求

/**
 * get请求设置请求头
 * @return
 */
public static String doGet(String url, Map<String,String> header){
    if(header == null){
        throw new RuntimeException("head is not allowed null");
    }
    HttpGet httpGet = new HttpGet(url);
    //添加header
    for (Map.Entry<String, String> e : header.entrySet()) {
        httpGet.addHeader(e.getKey(), e.getValue());
    }
    httpGet.setConfig(DEFAULT_CONFIG);
    return request(httpGet);
}

Post请求提交form表单

/**
 * post请求 form表单方式提交
 * @param url  url
 * @param params 参数
 * @param header 请求头
 * @return
 */
public static String doPost(String url, List<NameValuePair> params,Map<String,String> header){
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(DEFAULT_CONFIG);
    //默认form表单提交,可加可不加
    httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    if(params != null){
        //参数
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("utf-8"));
        httpPost.setEntity(entity);
    }
    //设置请求头
    addHeader(httpPost,header);
    return request(httpPost);
}

Post请求提交Json对象

/**
 * post请求 对象传参 ,key对应对象的字段名
 * @param url url
 * @param param 参数
 * @param header 请求头
 * @return
 */
public static String doPost(String url, JSONObject param,Map<String,String> header){
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(DEFAULT_CONFIG);
    httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
    //设置参数
    StringEntity stringEntity = new StringEntity(JSON.toJSONString(param),Charset.forName("utf-8"));
    httpPost.setEntity(stringEntity);
    //设置请求头
    addHeader(httpPost,header);
    return request(httpPost);
}

Httpclient下载文件

/**
 * 文件下载
 * @param url 文件url地址
 * @param header 请求头
 * @param fileName 写入本地的文件名称
 */
public static void downLoadFile(String url,Map<String,String> header,String fileName){
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
        HttpGet httpGet = new HttpGet(url);
        //添加请求头
        addHeader(httpGet,header);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)){
            log.info("响应状态:" + response.getStatusLine());
            HttpEntity httpEntity = response.getEntity();
            if(httpEntity != null){
                //获取输入流
                try (InputStream inputStream = httpEntity.getContent()){
                    Path path = Paths.get(DOWNLOAD_PATH + fileName);
                    //文件流存入本地目录
                    Files.copy(inputStream,path);
                }
            }
        }
    }catch (Exception e){
        log.error("下载文件错误",e);
    }
}

Httpclient文件上传

/**
 * 文件上传
 * @param url url
 * @param paramName 参数名称
 * @param inputStream 文件输入流
 * @param fileName 文件名称(上传接口获取到的名称)
 * @return
 */
public static String uploadFile(String url,String paramName,InputStream inputStream,String fileName){
    try {
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addBinaryBody(paramName,inputStream, ContentType.DEFAULT_BINARY,fileName);
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        return request(httpPost);
    }finally {
        try {
            inputStream.close();
        } catch (IOException e) {
           log.error("关闭InputStream输入流异常",e);
        }
    }
}

Httpclient多文件上传

/**
 * 多文件上传
 * @param url url
 * @param paramName 参数名称
 * @param filePath 文件夹目录(将这个文件夹一级子文件都上传)
 * @return
 */
public static String uploadFiles(String url,String paramName,String filePath){
    File file = new File(filePath);
    if(!file.exists() || !file.isDirectory()){
        return null;
    }
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for(File f : file.listFiles()){
        if(f.isFile()){
            multipartEntityBuilder.addBinaryBody(paramName,f, ContentType.DEFAULT_BINARY,f.getName());
        }
    }
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(multipartEntityBuilder.build());
    return request(httpPost);
}

全部代码HttpClientUtil

gitee地址:https://gitee.com/zhaoqingquan/httpclient

package com.example.demo.httpclient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zqq
 * @date 2021/4/28 17:09
 */
@Slf4j
public class HttpClientUtil {

    /**
     * 默认配置信息
     */
    private static RequestConfig DEFAULT_CONFIG;

    private static final String DOWNLOAD_PATH = "D:\\downloadtest\\";

    static {
        DEFAULT_CONFIG = RequestConfig.custom()
                //连接超时时间 毫秒
                .setConnectTimeout(5 * 1000)
                //请求超时时间 毫秒
                .setConnectionRequestTimeout(5 * 1000)
                //读写超时时间
                .setSocketTimeout(5 * 1000).build();
    }

    public static void main(String[] args) throws Exception{
        Map<String,String> head = new HashMap<>(1,1);
        head.put("testhead","head");
        String result = null;
        //1.get请求测试
        //result = doGet("http://127.0.0.1/test/testGet?param=这是参数");
        //2.get请求带头测试
        //result = doGet("http://127.0.0.1/test/testGet?param=testparam",head);
        //3.post请求 form表单提交测试   Content-Type=application/x-www-form-urlencoded; charset=UTF-8
        /*List<NameValuePair> params = new ArrayList<>(2);
        params.add(new BasicNameValuePair("name","zqq"));
        params.add(new BasicNameValuePair("sex","男"));
        result = doPost("http://127.0.0.1/test/testPost",params,head);*/
        //4.post请求 传对象测试 "Content-Type","application/json; charset=UTF-8"
        /*JSONObject paramJson = new JSONObject();
        paramJson.put("name","zqq");
        paramJson.put("sex","男");
        result = doPost("http://127.0.0.1/test/testPostObject",paramJson,null);*/
        //5.下载文件测试
        //downLoadFile("http://127.0.0.1/test/downtest",null,"431.png"); //接口下载文件测试
        //downLoadFile("https://profile.csdnimg.cn/B/5/9/0_zhaoqingquanajax",null,"head.png"); //下载网络文件测试
        //6.上传文件测试
       /* File file = new File("D:\\downloadtest\\123.png");
        InputStream inputStream = new FileInputStream(file);
        result = uploadFile("http://127.0.0.1/test/uploadTest","file",inputStream,file.getName());*/
        //7.多文件上传测试
        result = uploadFiles("http://127.0.0.1/test/uploadFiles","files","D:\\downloadtest\\");
        System.out.println(result);
    }

    /**
     * get请求
     * @param url url,参数拼接在后面 ?name=val&name1=var1
     * @return
     */
    public static String doGet(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(DEFAULT_CONFIG);
        return request(httpGet);
    }

    /**
     * get请求设置请求头
     * @return
     */
    public static String doGet(String url, Map<String,String> header){
        if(header == null){
            throw new RuntimeException("head is not allowed null");
        }
        HttpGet httpGet = new HttpGet(url);
        //添加header
        for (Map.Entry<String, String> e : header.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }
        httpGet.setConfig(DEFAULT_CONFIG);
        return request(httpGet);
    }

    /**
     * 发送请求
     * @param request 请求 HttpPost/HttpGet
     * @return string
     * @throws IOException
     */
    private static String request(HttpUriRequest request) {
        String result = null;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse response = httpClient.execute(request)
            ){
            log.info("响应状态:" + response.getStatusLine());
            HttpEntity httpEntity = response.getEntity();
            if(httpEntity != null){
                result = EntityUtils.toString(httpEntity, Charset.forName("utf-8"));
                log.info("响应内容:" + result);
            }
        }catch (Exception e){
            log.error("发送请求错误",e);
        }
        return result;
    }

    /**
     * post请求 form表单方式提交
     * @param url  url
     * @param params 参数
     * @param header 请求头
     * @return
     */
    public static String doPost(String url, List<NameValuePair> params,Map<String,String> header){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(DEFAULT_CONFIG);
        //默认form表单提交,可加可不加
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        if(params != null){
            //参数
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("utf-8"));
            httpPost.setEntity(entity);
        }
        //设置请求头
        addHeader(httpPost,header);
        return request(httpPost);
    }

    /**
     * post请求 对象传参 ,key对应对象的字段名
     * @param url url
     * @param param 参数
     * @param header 请求头
     * @return
     */
    public static String doPost(String url, JSONObject param,Map<String,String> header){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(DEFAULT_CONFIG);
        httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
        //设置参数
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(param),Charset.forName("utf-8"));
        httpPost.setEntity(stringEntity);
        //设置请求头
        addHeader(httpPost,header);
        return request(httpPost);
    }

    /**
     * 添加请求头
     * @param httpPost post请求
     * @param header 请求头
     */
    private static void addHeader(HttpRequestBase httpPost, Map<String,String> header){
        if(header == null || header.isEmpty()){
            return;
        }
        //添加header
        for (Map.Entry<String, String> e : header.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
    }

    /**
     * 文件下载
     * @param url 文件url地址
     * @param header 请求头
     * @param fileName 写入本地的文件名称
     */
    public static void downLoadFile(String url,Map<String,String> header,String fileName){
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
            HttpGet httpGet = new HttpGet(url);
            //添加请求头
            addHeader(httpGet,header);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)){
                log.info("响应状态:" + response.getStatusLine());
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity != null){
                    //获取输入流
                    try (InputStream inputStream = httpEntity.getContent()){
                        Path path = Paths.get(DOWNLOAD_PATH + fileName);
                        //文件流存入本地目录
                        Files.copy(inputStream,path);
                    }
                }
            }
        }catch (Exception e){
            log.error("下载文件错误",e);
        }
    }

    /**
     * 文件上传
     * @param url url
     * @param paramName 参数名称
     * @param inputStream 文件输入流
     * @param fileName 文件名称(上传接口获取到的名称)
     * @return
     */
    public static String uploadFile(String url,String paramName,InputStream inputStream,String fileName){
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody(paramName,inputStream, ContentType.DEFAULT_BINARY,fileName);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            return request(httpPost);
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
               log.error("关闭InputStream输入流异常",e);
            }
        }
    }

    /**
     * 多文件上传
     * @param url url
     * @param paramName 参数名称
     * @param filePath 文件夹目录(将这个文件夹一级子文件都上传)
     * @return
     */
    public static String uploadFiles(String url,String paramName,String filePath){
        File file = new File(filePath);
        if(!file.exists() || !file.isDirectory()){
            return null;
        }
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        for(File f : file.listFiles()){
            if(f.isFile()){
                multipartEntityBuilder.addBinaryBody(paramName,f, ContentType.DEFAULT_BINARY,f.getName());
            }
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(multipartEntityBuilder.build());
        return request(httpPost);
    }
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值