java實現自動化測試介面訪問(一)

java實現自動化測試介面訪問(一)

一、前置準備:

  1. PostMan
  2. 訪問的網站:Github
  3. 訪問的介面:
    https://api.github.com/search/commits?q=committer-date:2017-11-27..2017-12-01&page=1&per_page=100
  4. 實現訪問:查詢2017-11-27到 2017-12-01的100條資料

二、程式碼實現
1. 使用PostMan輸入訪問的介面,取得需要的欄位,items,和items中repository的欄位id,和full_name(可以自己獲取想要的欄位)
這裡寫圖片描述

  1. java類
    (1)、CommitRepo
public class CommitRepo {
private String id;
private String full_name;
@Override
public String toString() {
return "CommitRepo [id="   id   ", full_name="   full_name   "]";
}
public String getId() {
return id;
}
public String getFull_name() {
return full_name;
}
}

(2)、CommitItems

public class CommitItems {
private CommitRepo repository;//名字要一樣(repository)
public CommitRepo getRepository() {
return repository;
}
@Override
public String toString() {
return "CommitItems [repository="   repository   "]";
}
}

(3)、GithubCommitsResult

public class GithubCommitsResult {
private CommitItems[] items;
public CommitItems[] getItems() {
return items;
}
@Override
public String toString() {
return "GithubCommitsResult [items="   Arrays.toString(items)   "]";
}
}

(4)、GithubTest測試類

public static void main(String[] args) {
try {
URL url = new URL("https://api.github.com/search/commits?q=committer-date:2017-11-27..2017-12-01&page=10&per_page=100");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();// 開啟連線            
https.addRequestProperty("Accept","application/vnd.github.cloak-preview");// 設定請求屬性
https.addRequestProperty("Authorization", "Basic " up);
https.setDoInput(true);
InputStream is = https.getInputStream();
Gson gson = new GsonBuilder().create();
GithubCommitsResult gcr = gson.fromJson(new InputStreamReader(is),GithubCommitsResult.class);
for(int i=0;i<gcr.getItems().length;i  ){
System.out.println(gcr.getItems()[i].getRepository().getId());
}
is.close();
https.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

(5)、GithubTest測試類程式碼修改

public static void main(String[] args) {
String url="https://api.github.com/search/commits?q=committer-date:2017-11-27..2017-12-01&page=1&per_page=100";
String ret=getGithubApiReply(url);
Gson gson = new GsonBuilder().create();
GithubCommitsResult gcr = gson.fromJson(ret,GithubCommitsResult.class);
System.out.println(gcr.getItems()[99].getRepository().getId());
}
public static String getGithubApiReply(String api_url) {
String retstr = null;
try {
URL url = new URL(api_url);
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();// 開啟連線
https.addRequestProperty("Accept",
"application/vnd.github.cloak-preview");// 設定請求屬性       
https.setDoInput(true);
InputStream is = https.getInputStream();
Reader reader = new InputStreamReader(is, "utf-8");
StringBuffer sb = new StringBuffer();
int c = -1;
while ((c = reader.read()) != -1) {
sb.append((char) c);
}
retstr = new String(sb);
is.close();
https.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return retstr;
}