LoginSignup
2
5

More than 5 years have passed since last update.

unirestでWeb APIからデータを簡単に取得する。

Posted at

最近、GitHub APITwitter API等のWeb APIから情報を取得することが多くなっています。

対応するライブラリGitHubがあるのですがAPI仕様が変わったりした時に追随できていないことがあったりします。

もっと自由にデータを取得したい時にはunirestを使ってデータを取得しています。

データの取得

GitHub Issues取得時
curlで投げる感覚で記述していきます。

uniGetIssues.java

        HttpResponse<JsonNode> jsonResponse = Unirest.get("https://api.github.com/repos/" + REPOSITRY + "/issues")
                .basicAuth(GITHUB_USER, GITHUB_PASSWORD)
                .header("accept", "application/json")
                .queryString("sort", "created")
                .queryString("direction", "dsc")
                .asJson();

        if (jsonResponse.getStatus() != 200) {
            throw new HttpException(jsonResponse.getStatusText());
        }
        return jsonResponse.getBody();

asJson()を使うことでJSON形式でデータが取得でき、JSON Parseを自分でする必要がなくなります。

またレスポンスはJSONArrayで普通のArrayのように扱うことができます。

uniGetResponse.java

        HashMap<String,ArrayList<Issue>> gitHubIssues = new HashMap<>();

        JSONArray array = jsonResponse.getArray();
        Iterator<Object> ite = array.iterator();

        while (ite.hasNext()) {
            JSONObject json = (JSONObject)ite.next();

            JSONArray label = json.getJSONArray("labels");
            System.out.println(json.get("number").toString() + "assinee:" + json.get("assignee").toString() + ":size:" + json.getJSONArray("assignees").length());
            Iterator<Object> lite = label.iterator();
            if (!lite.hasNext()) {
                continue;
            }

            JSONObject ljson = (JSONObject)lite.next();

            JSONArray assignees = json.getJSONArray("assignees");

            Iterator<Object> assignee = assignees.iterator();
            while (assignee.hasNext()) {
                String assineeName = null;
                String issueNumber = null;
                String updatedAt = null;

                JSONObject jassignee = (JSONObject)assignee.next();

                assineeName = jassignee.get("login").toString();
                issueNumber= json.get("number").toString();
                updatedAt = json.get("updated_at").toString();

                Issue issueEntity = new Issue();
                issueEntity.setAssignee(assineeName);
                issueEntity.setNumber(issueNumber);
                issueEntity.setTitle(json.get("title").toString());

                if (ljson.get("name").equals("doing")) {
                    issueEntity.setDoingDateFrom(updatedAt);
                } else if (ljson.get("name").equals("review")) {
                    issueEntity.setReviewDateFrom(updatedAt);
                } else if (ljson.get("name").equals("done")) {
                    issueEntity.setDoneDateAt(updatedAt);
                }

                try {
                    JSONArray pull_requests = json.getJSONArray("pull_request");
                    Iterator<Object> pull_request= pull_requests.iterator();
                    while (pull_request.hasNext()) {
                        JSONObject jpull_request = (JSONObject)pull_request.next();
                            issueEntity.setPullRequestUrl(jpull_request.get("url").toString());
                            issueEntity.setPullRequestDateFrom(updatedAt);
                    }
                } catch(JSONException e) {
                    //System.out.println("pull_request not found");
                }

                ArrayList<Issue> newIssueList = gitHubIssues.get(assineeName);
                if (null == newIssueList) {
                    newIssueList = new ArrayList<>();
                }

                newIssueList.add(issueEntity);
                gitHubIssues.put(assineeName, newIssueList);
            }
        }

proxyがある会社内から投げたい場合はsetProxyメソッドでproxyを超えることが出来るようになります。

        Unirest.setProxy(new HttpHost("proxyホスト", proxyポート));
        HttpResponse<JsonNode> jsonResponse = Unirest.get("https://api.github.com/repos/" + REPOSITRY + "/issues")
                .basicAuth(GITHUB_USER, GITHUB_PASSWORD)
                .header("accept", "application/json")
                .queryString("sort", "created")
                .queryString("direction", "dsc")
                .asJson();

うちもそうなのですがproxyにユーザ認証がある場合はこんな感じになります。


        String proxy_host = System.getProperty("http.proxyHost");
        if (proxy_host != null) {
            int proxy_port = Integer.parseInt(System.getProperty("http.proxyPort"));
            HttpHost proxy = new HttpHost(proxy_host, proxy_port);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            String proxy_user = System.getProperty("http.proxyUser");
            String proxy_password = System.getProperty("http.proxyPassword");
            credsProvider.setCredentials(
                    new AuthScope(proxy),
                    new UsernamePasswordCredentials(proxy_user, proxy_password));
            RequestConfig config = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();

            HttpClient httpclient = HttpClients.custom()
                    .setDefaultCredentialsProvider(credsProvider)
                    .setDefaultRequestConfig(config)
                    .build();
            Unirest.setHttpClient(httpclient);
        }

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5