eclipse中客戶端介面呼叫框架--HttpClient
HttpClient是一個實現了http協議的客戶端介面呼叫的技術,可以通過他來模擬測試工具發出介面請求,完成介面呼叫。
1.整合eclipse(maven)專案的依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
2.介面呼叫步驟
//指定介面地址的是請求地址
//指定介面的請求方式:post //準備測試資料 //在post請求中將測試資料注入 //發起請求,獲取介面響應資訊(狀態碼,響應報文等) //相當於傳送按鈕 //獲取響應結果 //獲取響應結果的狀態碼 //獲取響應結果的報文體
public static void main(String[] args) throws ClientProtocolException, IOException { //指定介面地址的是請求地址 String url="http://119.23.241.154:8080/futureloan/mvc/api/member/login"; //指定介面的請求方式:post
HttpPost post=new HttpPost(url); //準備測試資料 String mobilephone="13121822321"; String pwd="123456"; List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("mobilephone", mobilephone)); parameters.add(new BasicNameValuePair("pwd", pwd)); HttpEntity entity=new UrlEncodedFormEntity(parameters,"utf-8"); //在post請求中將測試資料注入 post.setEntity(entity); //發起請求,獲取介面響應資訊(狀態碼,響應報文等) //相當於傳送按鈕 HttpClient client=HttpClients.createDefault(); //獲取響應結果 HttpResponse response=client.execute(post); //獲取響應結果的狀態碼 int code=response.getStatusLine().getStatusCode(); //獲取響應結果的報文體 String result=EntityUtils.toString(response.getEntity()); System.out.println(code);System.out.println(result);
public class GetDemo { public static void main(String[] args) throws ClientProtocolException, IOException { //準備介面地址 String url="http://119.23.241.154:8080/futureloan/mvc/api/member/login"; //準備測試資料 String mobilephone="13121822321"; String pwd="123456"; //url拼接 url+="?"+mobilephone+"&"+pwd; //指定介面的請求方式 HttpGet httpGet=new HttpGet(url); //發起請求 HttpClient client=HttpClients.createDefault(); //請求返回值需要用發起的請求的execute方法 HttpResponse response=client.execute(httpGet); //響應資料的狀態碼 int code=response.getStatusLine().getStatusCode(); //響應資料的報文體 String result=EntityUtils.toString(response.getEntity()); System.out.println(code); System.out.println(result); }