我必须打开一个Postman并使用GET选项传递Url。它将生成一个Json数据。我必须阅读并与现有数据进行比较。 所以任何人都可以帮助我? 感谢
答案 0 :(得分:0)
据我了解,您正在尝试将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();
}
}
}