我正在尝试创建一个访问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();
}
我相信可以通过添加另一个标头/ requestProperty来完成,但我不确定如何。
非常感谢您的帮助
答案 0 :(得分:0)
以下代码适用于我:
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授权。