美文网首页
Java模拟Http请求

Java模拟Http请求

作者: ZainZhang | 来源:发表于2018-08-31 13:18 被阅读0次

本文使用的是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();
    }

}

相关文章

  • JAVA服务通过URL下载文件

    概述 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。 Java有原生...

  • Java模拟Http请求

    本文使用的是org.apache.httpcomponents中的httpclient,因为post请求涉及到传输...

  • java里模拟http请求

    早准备写这个了,因为java里模拟http请求的场景太多了,经常写,每次都百度粘贴。一直想自己完完整整写一个htt...

  • JAVA NIO模拟HTTP请求

    前言 使用JAVA NIO模拟请求百度,需要了解的概念 SocketChannel教程 Buffer教程 Sele...

  • Https实现机制详解

    Https请求 一、访问HTTPS站点 两种方法来模拟发送HTTP请求,访问HTTP站点。一种方式是通过java....

  • 模拟Http请求

    使用Telnet模拟Http请求 打开cmd运行框,输入Telnet www.baidu.com 80后按回车键。...

  • Java模拟post请求上传文件

    Java模拟post请求上传文件 Java代码实现/** * 模拟文件post上传 * @para...

  • 基于HttpClient的多线程上传

    了解HttpClient HttpClient是一个用来模拟浏览器发送http请求的java实现。我们可以通过编写...

  • 自动模拟HTTP请求

    客户端如果要与服务器端进行通信,需要通过http请求进行,http请求有很多种,主要的有post和get两种请求方...

  • postman模拟HTTP请求

    APP开发过程中,手机端与服务端由不同 的人员负责,服务器开发好的服务怎么测试呢?其实很简单,postman可以很...

网友评论

      本文标题:Java模拟Http请求

      本文链接:https://www.haomeiwen.com/subject/qcuswftx.html