接口测试-Java代码实现接口请求并封装

前言:

在接口测试和Java开发中对接口请求方法进行封装都非常有必要,无论是在我们接口测试的时候还是在开发自测,以及调用某些第三方接口时,都能为我们调用和调试接口提供便捷;

Java实现对http请求的封装

一,针对常见的json数据的http-post请求进行封装工具类的实现如下:

ackage com.nuanshui.frms.pre.demo.utils;


import com.nuanshui.frms.exchange.demo.utils.SSLProtocolSocketFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequestUtil
{
/**
 * HTTP请求
 * @param surl 接口请求url
 * @param json 接口请求body-json字符串
 *  
 * @return 接口返回结果
 */
    public static String sendJsonWithHttp(String surl, String json) throws Exception
    {
        URL url = new URL(surl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setRequestMethod("POST");// 提交模式
        conn.setRequestProperty("Content-Length", json.getBytes().length + "");
        conn.setConnectTimeout(100000);// 连接超时单位毫秒 //
        conn.setReadTimeout(200000);// 读取超时 单位毫秒
        conn.setDoOutput(true);// 是否输入参数
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(json.getBytes());
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line);
        }
        reader.close();
        conn.disconnect();

        return sb.toString();
    }
}

二,观察系统中的接口,我们会发现除了后面的路径不一样,其根路径都是一样的,于是我们可以将路径拆分为根路径+详细子路径,这样我们进行环境切换时(即根目录切换)很方便,因为接口子路径一旦确定一般情况下不会再变更,所以可以像下面一样进行路径变量常量化,如下所示:

public class FrmsUtils {
   public final static String URL = "http://www.baidu.com/";
    public final static String QUERY_WHITELIST_URL = "whiteList";//白名单接口
}

三,现在我们已经完成了接口调用方法的封装和路径管理,我们现在只需要编写调用某个http接口的实际调用类了,直接使用HttpRequestUtil.sendJsonWithHttp()方法就能进行调用哦,详细使用方式如下:

import com.nuanshui.frms.pre.demo.FrmsUtils;
import com.nuanshui.frms.pre.demo.utils.HttpRequestUtil;
import com.nuanshui.frms.pre.demo.utils.HttpUtils;
import com.nuanshui.frms.pre.demo.utils.KeyAndValue;
import net.sf.json.JSONObject;
import sun.applet.Main;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

public class WhiteListQueryDemo {

    public static void main(String[] args) {
        String validatePhone="1562397271";//接口入参
        String res;
        try {
           JSONObject jsonObject= new JSONObject();//new一个json对象
           jsonObject.put("phoneNum",validatePhone);//将入参添加进去,多个参数就put多个
            System.out.println(jsonObject.toString());//将json对象转换成字符串
            System.out.println("URL: "+FrmsUtils.URL+ FrmsUtils.QUERY_WHITELIST_URL);//打印组合后的路径;
            res = HttpRequestUtil.sendJsonWithHttp(FrmsUtils.URL+ FrmsUtils.QUERY_WHITELIST_URL,jsonObject.toString());//调用封装的请求方法,实现接口请求
            System.out.println(res);//打印接口返回结果
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行main方法就能成功调用接口啦在日志中就能查看接口返回结果哦

上面一个接口的调用,可能封装的优点还没显现,但当我们需要调用另一个接口时,调用该方法时,优点就很明显了,我们只需要同二一样再编写一个类,就能实现了,是不是发现封装请求方法后,编写一个调用接口的请求类变得很简单了呢~

以上~对你有帮助的话,点个喜欢❤️吧~~

欢迎关注我的同名简书,博客,Github~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,269评论 25 708
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,591评论 8 265
  • 原来我们都会有长大的样子 我们的昨天都已远去 于是又再来一个轮回 重复往日的星光 人总要成长 可能仅仅由于那一丝丝...
    孙四又阅读 266评论 0 0
  • 大雪纷纷扬扬,下了几天。上午时,我一个人去医院看病。雪花落在地上,新鲜的雪花落在地上,像盐一样,干燥松软,整个心都...
    木辛草明阅读 279评论 2 1