http接口测试mark(1)

    xiaoxiao2021-12-14  19

    最近在做支付产品的外部接口测试,接口提供给商户后台调用。这些接口有些共性,都用到了http post json和X.509证书签名。接口测试时借用了一些工具,loadrunner VUG、fiddler、Jmeter等,但是后来发现还是eclipse更方便自由。代码能力太弱,但还是凑出了2个方法方便测试时调用,mark一下。

    代码块

    package util; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import javax.swing.text.html.HTMLDocument.Iterator; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONObject; import Certificate.CertificateCoder; public class xxxUtil { /*map2req方法:根据接口入参map、证书路径、密钥,自动计算签名、且拼装出json串*/ public static JSONObject map2json(LinkedHashMap map, String path, String pwd) throws Exception { String string = ""; LinkedHashMap<String, String> imap = map; Set set = imap.entrySet(); java.util.Iterator i = set.iterator(); for (int k = 1; i.hasNext(); k++) { Map.Entry me = (Map.Entry) i.next(); if (k < imap.size()) { string = string + me.getKey() + "=" + me.getValue() + "&"; } else string = string + me.getKey() + "=" + me.getValue(); } String sign = CertificateCoder.sign(string, path, pwd);//调用开发提供的签名方法 imap.put("sign", sign); JSONObject req = (JSONObject) JSONObject.toJSON(imap); return req; } /*httpPostJson方法:传入url地址和json串,自动发送请求。*/ public static void httpPostJson(String uri, JSONObject req) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(uri); JSONObject jsonParam = new JSONObject(req); StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); System.out.println("Response content: " + EntityUtils.toString(entity2)); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); } } finally { httpclient.close(); } } /*调用示例*/ public static void main(String[] args) throws Exception { JSONObject req = map2json(autoData.whp0001(), "k:/xxxxx.pfx", "xxxxxxx"); /*autoData.whp0001(),按某接口设计写的方法,用来自动生成测试数据*/ System.out.println("Request content: " + req1); httpPostJson("http://xxxxxxxxxxxxxxxxx", req); } }
    转载请注明原文地址: https://ju.6miu.com/read-971114.html

    最新回复(0)