前言
在接口测试和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方法就能成功调用接口啦~在日志中就能查看接口返回结果哦~

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

以上~对你有帮助的话,点个赞

04-28 13:45