您好,登錄后才能下訂單哦!
在做http接口測試的時候,老是要做一大堆的參數和值,整個界面看著相當別扭,于是就把參數部分組合放到一個方法中,把執行放到一個方法中,主函數就只要獲取response字符串做處理做斷言就好了,這樣這個代碼看上去清爽多了,這里用到了httpclient、dom4j、testng的jar包。
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.testng.AssertJUnit;
public class HttpInterfaceTest {
private static String url;
private static String[][] keyVlaueList = {{"cdkey","6SDK"},{"password","160489"}}; //根據需要自定義接口參數個數及參數值
private static List<NameValuePair> postPara = new ArrayList<NameValuePair>();
private static String responseEntiy;
/**
* 組裝請求參數
* @param keyVlaueList
*/
public static List<NameValuePair> getPostPara(String[][] keyVlaueList) throws DocumentException{
for(int i = 0;i<keyVlaueList.length;i++)
{
postPara.add(new BasicNameValuePair(keyVlaueList[i][0],keyVlaueList[i][1]));
}
return postPara;
}
/**
* 獲取接口返回字符串
* @param url
*/
public static String getResponse(String url){
try {
postPara = getPostPara(keyVlaueList);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(postPara));
CloseableHttpResponse response = httpclient.execute(post);
HttpEntity entiyResponse = response.getEntity();
responseEntiy = EntityUtils.toString(entiyResponse).trim();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (DocumentException e) {
e.printStackTrace();
}
return responseEntiy;
}
public static void main(String[] args){
url = "http://xxxxxxx/querybalance.action";
responseEntiy = getResponse(url);
//獲取的字符串:responseEntiy = <?xml version="1.0" encoding="UTF-8"?><response><error>0</error><message>1442.4</message></response>
//根據接口返回的字符類型做相應的解析,自由發揮!
try {
Document document = DocumentHelper.parseText(responseEntiy);
Element rootElement = document.getRootElement();
Element nodeElement = rootElement.element("error");
String errorString = nodeElement.getTextTrim();
if (!errorString.equals("0")){
AssertJUnit.fail(responseEntiy);
}
}catch (DocumentException e) {
e.printStackTrace();
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。