使用 REST 从 Web 服务接收数据 API

Receive data from a webservice using REST API

我需要从这个 API http://countryapi.gear.host/v1/Country/getCountries?pName=Australia 中获取特定数据,将其转换为 String 并在控制台上写出。我只想获取澳大利亚的数据。我怎样才能只为 Name 和 Alpha2Code 获取字符串格式的数据,如下所示: Australia, AU?我试图使用 EntityUtils.toString(response) 但它不起作用。

这是我的代码:

public class Client {

public static void main(String[] args) throws ClientProtocolException, IOException {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
    request.addHeader("accept", "application/json");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    String line = reader.readLine();
    System.out.println(line);
}
}

澳大利亚的代码实际上return JSON,像这样:

enter image description here

您可以使用 java api 进行 json 解析。我只是在写一个示例代码。您可以在下方 URL 探索 json 解析 api 的更多信息: http://www.oracle.com/technetwork/articles/java/json-1973242.html

JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)) {
    System.out.print(result.getJsonObject("name").getString("name"));
    System.out.print(": ");
    System.out.println(result.getString("message", ""));
    System.out.println("-----------");
 }

尝试这样的事情:

Gson gson = new Gson();
JsonObject result = gson.fromJson(line, JsonObject.class);
JsonArray response = result.getAsJsonArray("Response");
Country country = gson.fromJson(response, Country.class);