继上一篇SoapUI对webservice进行功能测试,补充用httpclient对webservice进行测试,将返回的数据写到xml中便于查看
@Test
public void test1() throws ClientProtocolException, IOException{
String file_dir="./File";
String file="./File/format_xml.xml";
//wsdl地址:
String url="http://interfacegscapp.salesappcn.com/axis2/services/Ebusiness?wsdl";
//输入的数据格式:
String data="[{\"ID\":\"201403041008153769\",\"ProjectID\":\"123456\",\"companyNumber\":\"00000\",\"createtime_cus\":\"20140304100815\",\"mobile\":\"13800136103\",\"name\":\"ligang\",\"resouce\":\"1\"}]";
//返回的xml数据
String conResult =null;
//拼写URL
String soapReuqest="<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:axis=\"http://ws.apache.org/axis2\">"
+"<soap:Header/>"
+"<soap:Body>"
+" <axis:transCus>"
+"<axis:url>"+data+"</axis:url>"
+"</axis:transCus>"
+"</soap:Body>"
+"</soap:Envelope>";
//1.创建请求
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.获取httppost
HttpPost httppost = new HttpPost(url);
//3.然后把SOAP请求数据添加到postmethod方法中
byte[] b =soapReuqest.getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b,0,b.length);
InputStreamEntity reqEntity =new InputStreamEntity(is,b.length);
httppost.setEntity(reqEntity);
HttpResponse response=httpclient.execute(httppost);
int statuscode=response.getStatusLine().getStatusCode();
if(statuscode==200){
System.out.println("调用成功!");
//读返回数据,将数据写入到xml文件中
conResult = EntityUtils.toString(response.getEntity());
writeStrToFile.writeStrToFile(conResult,file_dir,file);
}else{
System.out.println("调用失败!错误码:"+statuscode);
}
//ReadXML.ReadXml(file);
httpclient.close();
}
封装类:将数据写xml中
/**
* 先判断文件及目录是否存在;
* 将String类型的字符串写入到xml中
* */
public static void writeStrToFile(String xml,String file_dir,String file){
try {
File outfile = new File(file);
File Direct = new File(file_dir);
//如果文件夹不存在则创建
if (!Direct .exists() && !Direct .isDirectory())
{
System.out.println("File不存在");
Direct .mkdir();
} else
{
System.out.println("File目录存在");
}
if(!outfile.isFile()){
System.out.println("format_xml.xml创建成功");
outfile.createNewFile();
}else{
System.out.println("format_xml.xml文件存在,删除并重新创建文件");
outfile.delete();
outfile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(new File(file));
Writer os = new OutputStreamWriter(fos,"utf-8");
os.write(xml);
os.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
返回来的结果:
调用成功!
<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><ns:transCusResponse xmlns:ns="http://ws.apache.org/axis2"><ns:return>1</ns:return></ns:transCusResponse></soapenv:Body></soapenv:Envelope>
File目录存在
format_xml.xml文件存在,删除并重新创建文件
PASSED: test1
生成的文件:
依赖包:testng、HttpClient(4.3)、dom4j