import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class HttpClientTest {
// 使用Excel数据驱动取数据,TestNG的DataProvider注解提供数据非常方便,实现原理不必深究,它会自动调用ExcelDataProvider并返回一个Map给测试方法,如果使用DataProvider的Excel做数据驱动,应将测试方法的参数指定为Map
@DataProvider(name = "datapro")
public Iterator<Object[]> Data() {
return new ExcelDataProvider("SoapTest", "testSoap");
}
@Test(dataProvider = "datapro")
public void httpPost(Map<String, String> data) throws IOException {
// 对传输数据进行加密,这里使用SHA-1算法加密
SoapKey soapKey = new SoapKey();
String key = soapKey.getMessageDigest(data.get("data"), "SHA-1");
// 将请求XML主体数据的"<"与">"替换成"<"与">"
String strData = new String(data.get("data").replace("<", "<")).replace(">", ">");
// 请求的XML数据
String soapReuqest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.ws.gpo.yy.com/\">"
+ "<soapenv:Header/>" + "<soapenv:Body><ser:sendRecv4Supplier><!--Optional:--><sUser>"
+ data.get("user") + "</sUser><!--Optional:--><sPwd>" + data.get("passwd")
+ "</sPwd><!--Optional:--><sJgbm>" + data.get("jgbm")
+ "</sJgbm><!--Optional:--><sVersion>1.0.0.0</sVersion><!--Optional:--><sXxlx>" + data.get("msgType")
+ "</sXxlx><!--Optional:--><sSign>" + key + "</sSign><!--Optional:-->" + "<xmlData>" + strData
+ "</xmlData>" + "</ser:sendRecv4Supplier></soapenv:Body></soapenv:Envelope>";
// 1.创建httpClient客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
// 2.获取http post
HttpPost httppost = new HttpPost(data.get("urlStr"));
// 3.设置发送请求的字符集编码,如果不指定,就会默认以16进制的字符集编码发送,返回的响应结果就会乱码
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + "utf-8");
// 4.把SOAP请求数据添加到http post方法中
byte[] by = soapReuqest.getBytes("utf-8");
InputStream inputStream = new ByteArrayInputStream(by, 0, by.length);
InputStreamEntity reqEntity = new InputStreamEntity(inputStream, by.length);
httppost.setEntity(reqEntity);
// 5.执行http post请求
HttpResponse response = httpclient.execute(httppost);
// 6.获取服务端返回的状态码
int statuscode = response.getStatusLine().getStatusCode();
// 7.获取服务器的返回实体
HttpEntity entity = response.getEntity();
//8.将服务器返回的实体转化成字符串(请求响应结果)
String responseMsg = EntityUtils.toString(entity);
System.out.println("接口:" + data.get("msgType") + ":返回的状态码与响应结果:" + statuscode + ":" + responseMsg);
}
}