致电Java获取书籍详细信息

用户13734449:

有一种HTTP GET方法可从中检索信息book db此处的查询响应是分页的,并进一步按字符串&page = num进行查找,num是页码。

给定一串所有者,getOwnerDetails必须执行以下操作:

Query : https://x.com/api/book?owner=<ownerNmae> 初始化details数组以存储字符串元素列表。

使用以下命令将在数据字段中返回的每本书的名称存储到详细信息目录:

  1. 如果title和story_title都为空,则忽略该书。

要么,

  1. 如果title不为null,请使用title作为名称。
  2. 如果title为null,则story_title用作名称。

根据total_pages计数,通过分页获取所有数据,然后执行上述步骤。下面的功能将对完成的任务起作用Return array of titles

public static List<String> getOwnerDetails(String book){
}

我曾尝试这样做,但无法完全获得数据调用。JSON数据:

{
    "page": 1,
    "per_page": 10,
    "total": 3,
    "total_pages": 1,
    "data": [{
        "title": "A Message to Our Customers",
        "url": "http://www.apple.com/customer-letter/",
        "author": "epaga",
        "num_comments": 967,
        "story_id": null,
        "story_title": null,
        "story_url": null,
        "parent_id": null,
        "created_at": 1455698317
    }, {
        "title": "“Was isolated from 1999 to 2006 with a 486. Built my own late 80s OS”",
        "url": "http://imgur.com/gallery/hRf2trV",
        "author": "epaga",
        "num_comments": 265,
        "story_id": null,
        "story_title": null,
        "story_url": null,
        "parent_id": null,
        "created_at": 1418517626
    }, {
        "title": "Apple’s declining software quality",
        "url": "http://sudophilosophical.com/2016/02/04/apples-declining-software-quality/",
        "author": "epaga",
        "num_comments": 705,
        "story_id": null,
        "story_title": null,
        "story_url": null,
        "parent_id": null,
        "created_at": 1454596037
    }]
}

我的代码::

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Scanner;

    public class Pr4 {
        public static void main(String[] args) throws IOException {
            String response = "";

            try {
                URL url = new URL("https://x.com/api/book?owner=epaga");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();
                int responsecode = conn.getResponseCode();
                System.out.println("Response code is: " + responsecode);

                if (responsecode != 200)
                    throw new RuntimeException("HttpResponseCode: " + responsecode);
                else {
                    Scanner sc = new Scanner(url.openStream());
                    while (sc.hasNext()) {
                        response += sc.nextLine();
                    }
                    System.out.println("\nJSON Response in String format");
                    System.out.println(response);
                    sc.close();
                }

                JSONParser parse = new JSONParser();

                JSONObject jobj = (JSONObject) parse.parse(response);
                System.out.println("page ::  " + jobj.get("page"));
                System.out.println("per_page :: " + jobj.get("per_page"));
                System.out.println("total :: " + jobj.get("total"));
                System.out.println("total_pages ::  " + jobj.get("total_pages"));
                JSONArray jsonarr_1 = (JSONArray) jobj.get("data");
                for (int i = 0; i < jsonarr_1.size(); i++) {
                    JSONObject jsonobj_1 = (JSONObject) jsonarr_1.get(i);
                    System.out.println("Elements under data array");
                    System.out.println("\nTitle: " + jsonobj_1.get("title"));
                    System.out.println("URL: " + jsonobj_1.get("url"));
                    System.out.println("author: " + jsonobj_1.get("author"));
                    System.out.println("Story_Title: " + jsonobj_1.get("story_title"));
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

之后,我需要调用以下函数以返回标题数组。

public static List<String> getOwnerDetails(String book){
}

JSON响应:页面,每页,总计,总计页面,数据(包含书籍信息的JSON对象数组)

如何用Java中上述方法的调用实现该调用?

一楼:

我得到了需要做的事情,并且得到了一些未包括的检查点的预期结果:

   import java.io.*;
    import java.util.*;
    import java.net.*;
    import com.google.gson.*;

    public class Solution{
        static List<String> getOwnerDetails(String book) {
            String response;
            int startPage = 1;
            int totalPages = Integer.MAX_VALUE;
            List<String> titles = new ArrayList<>();
            while (startPage <= totalPages) {
                try {
//Making own rest api as api is not getting invoked
                    URL obj = new URL(
                            "https://localhost:8080/greet?owner=" + book);
                    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                    con.setRequestMethod("GET");
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    while ((response = in.readLine()) != null) {
                        JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
                        totalPages = convertedObject.get("total_pages").getAsInt();
                        JsonArray data = convertedObject.getAsJsonArray("data");
                        for (int i = 0; i < data.size(); i++) {
                            String title = data.get(i).getAsJsonObject().get("title").getAsString();
                            titles.add(title);
                        }
                    }
                    in.close();
                    startPage++;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return null;
                }

            }
            Collections.sort(titles);
            return titles; // in case of string as list
        }

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

            List <String> res = new ArrayList<>();
            String book = "epaga";
            res = getOwnerDetails(book);

            for (int i = 0; i < res.size(); i++){
                System.out.println(res.get(i));
            }
        }
    }

未涵盖的问题,因为我没有得到该如何检查:

  1. 如果title和story_title都为空,则忽略该书。
  2. 如果title不为null,请使用title作为名称。
  3. 如果title为null,请使用story_title作为名称。

另外,如果我有.txt文件,可以在其中传递n个书本所有者,但我还是尝试这样做,但是以某种方式它失败了,没有错误:

Scanner in = new Scanner(System.in);
   File file = new File("\\Users\\rez\\a1.txt");

    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    String[] res;
    String book;
    try {
        book = in.nextLine();
    } catch (Exception e) {
       e.printStacktrace();
        book = null;
    }

如果有人可以检查从本地系统获取FileName的地方出了什么问题,我可以写n本书以通过,也可以考虑我留下的条件,这将是有帮助的。

Please be resolute in what and why you're doing

Modifications are also welcome in case if it is short and helpful

如果对此有见识,请致@author,请进行投票。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章