簡體   English   中英

如何驗證Github API的基本Java程序

[英]How to authenticate basic Java program for Github API

我正在嘗試創建一個訪問Github API並收集信息的基本Java應用程序。 我需要每小時能夠執行60多個請求,但不知道如何授權我的應用。 該應用程序不是公開的,不需要用戶身份驗證即可每小時訪問60個以上的請求。

到目前為止,我的代碼:

try {
            URL url = new URL("https://api.github.com/users/"+name);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");

            int responseCode = con.getResponseCode();
            String response = con.getResponseMessage();
            if(responseCode == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String content = reader.readLine();
                System.out.print(name + " - " + responseCode + " - " + response + " - " + content + "\n");
            }else{
                System.out.print(name + " - " + responseCode + " - " + response + "\n");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

我相信可以通過添加另一個header / requestProperty來完成,但不確定如何。

非常感謝您的幫助

以下代碼對我來說效果很好:

    package com.test.api.api;
    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.Response;
    import org.glassfish.jersey.client.ClientConfig;
    import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
    import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

    public class GitHub {

    public static void main(String[] args) {

    ClientConfig clientConfig = new ClientConfig();

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(
            "Your Email ID here", "Your Password");
    clientConfig.register(feature);

    Client client = ClientBuilder.newClient(clientConfig);
    WebTarget webTarget = client.target("https://api.github.com").path(
            "authorizations");

    String input = "{\"scopes\":[\"public_repo\"],\"note\":\"Ramanuj\"}";

    Response response = webTarget.request("application/json").post(
            Entity.json(input));
    System.out.println(response.readEntity(String.class));

        }
    }

您需要在pom.xml中具有以下依賴性

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.22.2</version>
    </dependency>

該代碼將在您的控制台中打印令牌,因此您可以在對github.com的后續請求中使用它

這等效於OAuth 2授權。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM