Authenticate http call to GitHub APIs in java - java

I'm working on a project which requires to call GitHub APIs several times and I reached the limit of 60.
I read that with authentication you get 5000 as limit but I can't understand how I can authenticate my requests in my java program. I got my authentication token on Github and this is the way I'm building the request in java:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.build();
what should I add to the request to authenticate it?
I tried adding the header authToken:myToken but it didn't work.

Solved:
Once I got the token on my GitHub profile > Settings > Developer Settings > Personal Access Tokens, I added the header `"Authorization: Bearer "myToken" " to the http request so the request becomes:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder().header("Authorization","Bearer <myToken>")
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.build();

You need to add Http request header Authorization to your request and the header should contain your token. So if your code is written on Java 11 or higher as it appears to be than you need to change your code to:
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.github.com/repos/:owner/:repo/commits"))
.header("Authorization", "your-tocken")
.build();

Related

Howto send PUT request without content and Content-Length header with Apache http client?

I'd like to test (via automated test) how server (and all proxies in-the-middle) responds to a PUT request without body and Content-Length header.
Similar to what curl does
curl -XPUT http://example.com
with Apache HTTP client (4.5.13)
But it looks like it always adds Content-Length header if I specify no body.
Is there any way to do that with Apache HTTP client?
Already tried (no luck)
final HttpPut request = new HttpPut(url);
request.removeHeaders("Content-Length");
Use a request interceptor to modify requests generated by the standard protocol processor
CloseableHttpClient httpClient = HttpClients.custom()
.addInterceptorLast((HttpRequestInterceptor) (request, context) ->
request.removeHeaders(HttpHeaders.CONTENT_LENGTH))
.build();
HttpPut httpPut = new HttpPut("http://httpbin.org/put");
httpClient.execute(httpPut, response -> {
EntityUtils.consume(response.getEntity());
return null;
});

Add Proxy to HttpRequest in java

I'm trying to understand how can I implement the use of a proxy for each request built like the following using Java API:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.createh("https://myurl"))
.timeout(Duration.ofMinutes(2))
.setHeader("User-Agent","Just an user agent")
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
I'm seeing from the doc (https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html#Asynchronous%20Example)
that is possible with Synchronous requests. My code is within a method and it will run with threads parallelly. So how is it possible to set a proxy with Asynchronous Requests? If it is not possible, what's the difference between them?
Solved, it's a bit unclear the doc about that but at the end, I was able to set the proxy when building the client:
HttpClient client = HttpClient.newBuilder().
proxy(ProxySelector.of(new InetSocketAddress("proxy",port))))
.build();
//The request code is identical to what I wrote above.
The method is newBuilder anyway and not Builder.

Why 400 error code in POST call using Jersey client

I am calling a post request using Jersey rest client which contains no request body but contains authorization header. I am always getting 400 error. I tried from postman i got 200 response. Here is my code
ClientResponse response = null;
Client cliente=Client.create();
cliente.addFilter(new LoggingFilter(System.out));
WebResource webResource=cliente.resource("https://URL/token");
Builder builder = webResource.accept("application/json");
builder.type(MediaType.APPLICATION_JSON);
builder.header("Authorization", "Basic YbjjkwliOTQtNjRiYy00NWE5LWFhMzQtMTFhNDkyZZjNTVlOjZjYjk2OTMwNGE5YTQ3OTlhODVjZTM5MDFiMDEyMTI2";
builder.post(ClientResponse.class,Entity.json(""));
Don't use the way you are trying right now. Use HttpAuthenticationFeature from Jersey like this
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");
 
final Client client = ClientBuilder.newClient();
client.register(feature);
If you are getting 200 success respone in postman and failure response in your application then you need to check your api with another api tester online tool. I had the same issue i put / at the last of end point.

Java HttpClient get redirect status of first redirect

I am trying to use HttpClient to make HTTP requests in Java. Whenever a url redirects me, I would like to know the status code of the original request and the final url. If I do not disable redirects, the status code is just the status code of the last successful request:
// google.com = tinyurl.com
HttpUriRequest httpUriRequest = new HttpGet("https://google.com/cqvga");
HttpClient httpClient =
HttpClientBuilder.create()
.build();
HttpResponse response = httpClient.execute(httpUriRequest);
System.out.println(response.getStatusLine().getStatusCode()); // 200
System.out.println(response.getHeaders(HttpHeaders.LOCATION).length); // 0
However, if I disable redirect handling then I get the redirect status:
HttpClient httpClient =
HttpClientBuilder.create()
.disableRedirectHandling()
.build();
System.out.println(response.getStatusLine().getStatusCode()); // 301
System.out.println(response.getHeaders(HttpHeaders.LOCATION).length); // 1
Is there anyway without me writing my own RedirectHandler to know the original status code of my first request, and the final url I landed on?

Need to send https GET request with oauth

I'm new to OAuth and trying to send a https GET request to retrieve something. Earlier I was using POSTMAN to test that and I was able to execute the GET request with OAUth 1.0 header authorization. The header authorization looks something as
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy86zlQg="
The query looks something as
https://secure.api.abc.net/DataService/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,yyyyy}
Note that I'm able to execute this fine from POSTMAN.
Now, I need to code that in java and I'm able to generate the oauth signature fine, but I'm wondering how do I set the authorization header after that in a https request???
Please advise as I'm new to oauth and want to learn.
I guess if your doing in Java, you will need to use the Apache HttpClient or something similar to make that request to the server and set the OAuth header to the request.
Code sample using the Apache HttpClient below.
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("OAuth", oauthHeaderString);
HttpResponse response = client.execute(request);

Categories

Resources