繼上一篇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