zoukankan      html  css  js  c++  java
  • 模拟postman开发的Http请求工具类

    模拟postman开发的http请求工具类

    开发语言:JAVA

    优点

    1、开箱即用、非常方便

    2、原生HTTP开发、对底层学习非常有帮助

    3、依赖极少,简单明了

    4、支持度高、灵活

    5、对自动化测试效率大大提高

    可支持属性

    属性 是否支持 备注
    请求方式 - -
    POST  
    GET  
    PUT  
    请求入参 - -
    Header设置  
    Body参数设置 目前支持form-data方式的文件上传、及json参数方式

    使用环境

    * 运行环境:jdk1.8.0_131
    * 依赖包:fastjson-1.2.7


    调用方法集合

     使用示例:

    请求Get示例

        public static void main(String[] args) throws IOException {
            String rs = PostmanUtils.sendGet("https://www.cnblogs.com/cheng2839");
            System.out.println(rs);
        }

    响应结果

    <!DOCTYPE html>
    <html lang="zh-cn">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="referrer" content="origin" />
        
        <meta http-equiv="Cache-Control" content="no-transform" />
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>温柔的星空,让你感动 - 博客园</title>
        <link id="favicon" rel="shortcut icon" href="//common.cnblogs.com/favicon.ico?v=20200522" type="image/x-icon" />
    
    由于返回内容太多,省略其余行

    请求POST示例(Body为json)

        public static void main(String[] args) throws IOException {
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("userName", "张三");
            bodyMap.put("userPass", "123456");
            String rs = PostmanUtils.sendPostJson("https://www.xxx.com/mywebapp/login.action", bodyMap);
            System.out.println(rs);
        }

    请求POST示例(Body为json,header中添加token)

            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("token", "4e654ff507be927c8ea55a");
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("userName", "张三");
            bodyMap.put("userPass", "123456");
            String rs = PostmanUtils.sendPostJson("https://www.xxx.com/mywebapp/login.action", headerMap, bodyMap);
            System.out.println(rs);

    请求POST示例(Body为form-data文件)

            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("file", "D:/001.jpg");
            String rs = PostmanUtils.sendPost("https://www.xxx.com/mywebapp/login.action",
                    PostmanUtils.CONTENT_TYPE_FORM_DATA, null, bodyMap);
            System.out.println(rs);

    等等不再此一一列举

    源码如下:

    package com.cheng2839.utils;
    
    import com.alibaba.fastjson.JSONObject;
    
    import javax.activation.MimetypesFileTypeMap;
    import java.io.ByteArrayOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 实现postman中主要请求方式
     *
     * 运行环境:
     * fastjson-1.2.7
     * jdk1.8.0_131
     *
     * @author cheng2839
     * @date 2020年7月2日
     */
    public class PostmanUtils {
    
        private static final int CONNECTION_TIMEOUT = 5000;
        private static final int READ_TIMEOUT = 30000;
        private static final boolean USE_CACHE = false;
        private static final String BOUNDARY = "----------------1234567890987654321";
    
        public static final String METHOD_POST = "POST";
        public static final String METHOD_GET = "GET";
    
        public static final String CONTENT_TYPE_FORM_DATA = "multipart/form-data;";
        public static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8;";
    
        private static HttpURLConnection CONNECTION;
    
        public static String sendGet(String url) throws IOException {
            return new String(send(url, METHOD_GET, CONTENT_TYPE_JSON, null, null));
        }
    
        public static byte[] sendGet(String url, Map<String, String> headerMap) throws IOException {
            return send(url, METHOD_GET, CONTENT_TYPE_JSON, null, null);
        }
    
        public static String sendGet(String url, String contentType,
                                      Map<String, String> headerMap, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_GET, contentType, headerMap, bodyMap));
        }
    
        public static String sendGetJson(String url, Map<String, String> headerMap, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_GET, CONTENT_TYPE_JSON, headerMap, bodyMap));
        }
    
        public static String sendGetJson(String url, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_GET, CONTENT_TYPE_JSON, null, bodyMap));
        }
    
        public static String sendPost(String url, String contentType,
                                      Map<String, String> headerMap, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_POST, contentType, headerMap, bodyMap));
        }
    
        public static String sendPostJson(String url, Map<String, String> headerMap, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_POST, CONTENT_TYPE_JSON, headerMap, bodyMap));
        }
    
        public static String sendPostJson(String url, Map<String, Object> bodyMap) throws IOException {
            return new String(send(url, METHOD_POST, CONTENT_TYPE_JSON, null, bodyMap));
        }
    
        public static byte[] send(String url, String method, String contentType,
                                  Map<String, String> headerMap, Map<String, Object> bodyMap)
                throws IOException {
    
            initHttpConnection(url, method);
    
            setHeader(contentType, headerMap);
    
            //setting json body
            if (bodyMap != null) {
                setBody(contentType, bodyMap);
            }
    
            return getResponse();
        }
    
        private static byte[] getResponse() throws IOException {
            // read return message
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            InputStream inputStream = CONNECTION.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while (-1 != (len = inputStream.read(buffer))) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            return byteArrayOutputStream.toByteArray();
        }
    
    
        private static String getContentTypeByFile(File file) {
            String fileName = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (isEmpty(contentType)) {
                contentType = "application/octet-stream";
            } else {
                String[] endSuffixes = {".png", ".gif", ".ico", ".jpg", ".jpeg", ".jpe"};
                String[] types = {"image/png", "image/gif", "image/image/x-icon", "image/jpeg"};
                contentType = "application/octet-stream";
                for (int i=0; i < endSuffixes.length; i++) {
                    if (fileName.toLowerCase().endsWith(endSuffixes[i])) {
                        contentType = types[Math.min(i, types.length-1)];
                        break;
                    }
                }
            }
    
            return contentType;
        }
    
        private static boolean isEmpty(String s) {
            return null == s || "".equals(s.trim());
        }
    }

    备注:该类无法直接使用,因为此为作者原创,版权原因(需要付费1元,备注postman工具,即可发至邮箱),如有需要可留言联系作者,请尊重作者时间和精力的耗费,见谅!

     特别注意:备注不规范无法发送,请备注【邮箱+postman工具】,例如:123456@126.com,postman工具 并请在您付款后2小时内查收邮件

    ____________________________特此,勉励____________________________
    本文作者cheng2839
    本文链接https://www.cnblogs.com/cheng2839
    关于博主:评论和私信会在第一时间回复。
    版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
    声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
  • 相关阅读:
    7行代码看EntityFramework是如何运行
    我用ASP.NET缓存之SQL数据缓存依赖(SqlCacheDependency)
    利用Microsoft.Office.Interop.Excel 将web页面转成PDF
    IT农民的开发人员工具清单(2013年)
    我在项目中运用 IOC(依赖注入)--实战篇
    我在项目中运用 IOC(依赖注入)--入门篇
    我用ASP.NET缓存之数据缓存
    我用ASP.NET缓存之OutputCache
    Resharper 使用帮助-自动生成文件头
    玩转变量、环境变量以及数学运算(shell)
  • 原文地址:https://www.cnblogs.com/cheng2839/p/13226309.html
Copyright © 2011-2022 走看看