如何使用硒从Postman读取Json数据
答
我了解你正在尝试在API响应回报JSON
格式比较数据
此代码可以帮助你 -
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.testng.annotations.Test;
public class WebAPITest
{
public static String url1="http://restcountries.eu/rest/v1";
@Test
public void getAPIRequest() throws Exception
{
try
{
URL url = new URL(url1);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if(conn.getResponseCode() != 200)
{
throw new RuntimeException(" HTTP error code : "+ conn.getResponseCode());
}
Scanner scan = new Scanner(url.openStream());
String entireResponse = new String();
while (scan.hasNext())
entireResponse += scan.nextLine();
System.out.println("Response : " + entireResponse);
scan.close();
System.out.println("API response Code : " + conn.getResponseCode() +"\t" + conn.getResponseMessage());
JSONArray jsonarray = new JSONArray(entireResponse);
for (int i = 0; i < jsonarray.length(); i++)
{
String countryname = jsonarray.getJSONObject(i).getString("name");
System.out.println("Country name : " + countryname);
JSONArray languages = jsonarray.getJSONObject(i).getJSONArray("languages");
System.out.print("Country languages : ");
for(int j=0;j<languages.length();j++)
{
System.out.print(languages.get(j) +" ");
}
System.out.println("");
String capital = jsonarray.getJSONObject(i).getString("capital");
System.out.println("Country Capital : " + capital);
}
conn.disconnect();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}