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

 

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

 

开发语言:JAVA

优点

1、开箱即用、非常方便

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

3、依赖极少,简单明了

4、支持度高、灵活

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

可支持属性

 

属性 是否支持 备注
请求方式 - -
POST  
GET  
请求入参 - -
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());
    }
}

 

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

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

 

posted @ 2020-07-02 18:17  温柔的星空,让你感动  阅读(1774)  评论(0编辑  收藏  举报