最近在做支付产品的外部接口测试,接口提供给商户后台调用。这些接口有些共性,都用到了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 {
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
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
}
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.whp 0001(), "k:/xxxxx.pfx" , "xxxxxxx" )
System.out .println ("Request content: " + req1)
httpPostJson("http://xxxxxxxxxxxxxxxxx" , req)
}
}