Java模拟Http请求

本文使用的是org.apache.httpcomponents中的httpclient,因为post请求涉及到传输文件,所以需要使用httpmime这个包

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.5.6</version>
</dependency>
<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.1</version>
</dependency>

直接上代码:

package com.yappam.gmcms.utils.web.tools;

import com.google.common.collect.Maps;
import com.yappam.gmcms.utils.encrypt.HmacUtil;
import com.yappam.gmcms.utils.string.StringUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.AbstractContentBody;
import org.apache.http.entity.mime.content.FileBody;
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.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * 类名称: HTTPUtils<br>
 * 类描述: Http请求<br>
 * 版权所有: Copyright (c) 2018/7/30 Zain Zhang, LTD.CO <br>
 * 创建时间: 2018/7/30 14:19 <br>
 *
 * @author zzy <br>
 * @version V1.0.0 <br>
 */
public class HttpUtils {
    public static final String ENCODING = "UTF-8";

    public static String get(final String url) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
//        //返回的数据包不进行压缩,解决content length为-1的问题
//        httpGet.setHeader("Accept-Encoding", "identity");
        System.out.println("executing get request " + httpGet.getURI());
        try {
            //执行get请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
                //获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    result = EntityUtils.toString(entity, ENCODING);
//                    System.out.println("Response content: " + result);
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }

        }catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String post(final String url, Map<String, Object> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        try {
            //获取请求的参数
            HttpEntity requestEntity = getRequestEntity(params);
            httpPost.setEntity(requestEntity);

            System.out.println("executing post request " + httpPost.getURI());
            //post请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                //获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    result = EntityUtils.toString(entity, ENCODING);
                    System.out.println("Response content: " + result);
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 通过参数获取HttpPost请求需要的参数
     * 如果参数有文件,则在key之前添加file_前缀,如要传的文件key为cover,则map的key为file_cover
     * @param params
     * @return
     */
    public static HttpEntity getRequestEntity(Map<String, Object> params) {
        Map<String, AbstractContentBody> paramsPart = Maps.newHashMap();
        //设置请求的参数
        params.entrySet().forEach(param -> {
            if (param.getKey().startsWith("file") && new File(param.getValue().toString()).isFile()) {
                paramsPart.put(param.getKey().split("_")[1], new FileBody(new File(param.getValue().toString())));
            }else {
                paramsPart.put(param.getKey(), new StringBody(param.getValue().toString(), ContentType.create("text/plain", Consts.UTF_8)));
            }
        });
        //拼接HttpEntity参数
        MultipartEntityBuilder requestEntityBuilder = MultipartEntityBuilder.create();
        paramsPart.entrySet().forEach(requestParam -> requestEntityBuilder.addPart(requestParam.getKey(), requestParam.getValue()));
        return requestEntityBuilder.build();
    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,338评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,650评论 25 709
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,854评论 1 92
  • 大理出差。 心情自然和游玩不同。 落脚处是洱海上游,“下关风”的地方,是一个相对繁华的新城区。 在宾馆加班,听着宾...
    李mu阅读 360评论 1 3
  • 这里有着别样 陌生的城市,熟悉而遥远的角落 生命的感恩,承载多少爱的记忆 噙着多少眼泪,十年了 多想来看看,我的亲...
    自由梦想的飞阅读 251评论 0 3

友情链接更多精彩内容