When sending okhttp request: HTTP ERROR 405 and invalid_client - java

I'm making a request to a website. However, I keep getting a returned JSON of {"error":"invalid_client"}. Additionally, when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
From what I read on those errors that might mean that my request isn't structured correctly.
According to the API's documentation, this is an example of the request type I'm trying to do:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "client_secret={your_client_secret}&client_id={your_client_id}&code={your_authorization_code}&grant_type=authorization_code&redirect_uri={your_redirect_uri}");
Request request = new Request.Builder()
.url("https://api.website.com/v2/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
From what I can tell mine should be doing the same thing, just a little differently.
Here is a Pastebin of my doInBackground method (I'm using AsynchTask). Here is the more applicable part:
OkHttpClient client = new OkHttpClient();
// A section here gets strings from a JSON file storing values such as client_id
RequestBody bodyBuilder = new FormBody.Builder()
.add("client_secret", CLIENT_SECRET)
.add("client_id", CLIENT_ID)
.add("code", AUTHORIZATION_CODE)
.add("grant_type", GRANT_TYPE)
.add("redirect_uri", REDIRECT_URI)
.build();
System.out.println("Built body: " + bodyBuilder.toString());
String mediaTypeString = "application/x-www-form-urlencoded";
MediaType mediaType = MediaType.parse(mediaTypeString);
RequestBody body = RequestBody.create(mediaType, requestbodyToString(bodyBuilder)); // See Edit 1
Request request = new Request.Builder()
.url(TARGET_URL)
.post(body)
.addHeader("content-type", mediaTypeString)
.addHeader("cache-control", "no-cache")
.build();
try {
System.out.println("Starting request.");
Response response = client.newCall(request).execute();
String targetUrl = request.url().toString() + bodyToString(request);
System.out.println("request: " + targetUrl);
String responseBodyString = response.body().string();
System.out.println("response: " + responseBodyString);
return responseBodyString;
} catch (IOException ex) {
System.out.println(ex);
}
Like I said, I keep getting a returned JSON of {"error":"invalid_client"}, and when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
I'd love to provide as much additional information as you need. Thanks!
Edit 1: The second parameter of this used to be "bodyBuilder.toString()", but I changed it because I realized it wasn't actually sending the body. The result is still the same - {"error":"invalid_client"}. The method now used comes from here.

I figured out what it was - I hadn't actually been writing the authentication_code to the file, only adding it to another JSONObject. Oops. :)

Related

okhttp call paybylink bad request but it does work in postman

I am trying to connect to pay by link by json.
We first tried with json and it worked like a charm.
I used the code postman provided to create this,
But we keep getting 400 bad request,
If we change the credentials we get unauthorized, se wo know it's not that
But if we go look in the request log of pay by link we see that the request send from java does not appear here at all, it does not show error, but nothing.
Does anybody know how we can fix it?
Thanks in advance!
Sincerely,
Laurens
try {
OkHttpClient client = new OkHttpClient();
client.setConnectionSpecs(Arrays.asList(
new ConnectionSpec[]{
new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.allEnabledCipherSuites()
.build()
}
));
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \"MappingTemplate\":\"test1\", \r\n\"OrderId\":\"NFA000053\",\r\n\"Description\":\"test#123.com\",\r\n\"Amount\":50,\r\n\"Gender\":\"Male\",\r\n\"Clientname\":\"Test\",\r\n\"Send\":\"nosend\"\r\n}");
Request request = new Request.Builder()
.url("https://testapi.paybylink.com/payment/create/abcdefghijkl.../")
.post(body)
.addHeader("Content-Type","application/json")
.addHeader("Authorization", credential)
.build();
Response response = client.newCall(request).execute();
System.out.println("request: " + request);
if(response.code()==400)
{
System.out.println("response: " + response);
}
} catch (Exception e) {
System.out.println("Exception occurred:- " + e.getMessage());
}

JAVA - How to build a client for OAuth 1.0 REST API with signature method as HMAC-SHA256?

I'm able to consume APIs (OAuth 1.0 Authorization & signature method as HMAC-SHA256) in POSTMAN, but not working JAVA (maven project).
Generated code from POSTMAN with OkHttp & Unirest libraries, both are not working. They give the following error.
403 Forbidden
I understand error is related to invalid authentication parameters. But not able to figure out what needs to be changed. Because same keys are working in Postman
OkHttp JAVA Code
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
RequestBody body = RequestBody.create(mediaType, JSONpayload);
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "OAuth realm=\"1111222_SB1\",oauth_consumer_key=\"xxxxxxxxx\",oauth_token=\"xxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxxxxx\"")
.addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING")
.build();
Response response = client.newCall(request).execute();
Unirest JAVA Code
Unirest.setTimeouts(0, 0);
String url = "https://www.example.com?script=508&deploy=1";
String JSONpayload = "{}";
HttpResponse<String> response = Unirest.post(url)
.header("Content-Type", "application/json")
.header("Authorization", "OAuth realm=\"1114415_SB1\",oauth_consumer_key=\"xxxxxxxxxx\",oauth_token=\"xxxxxxxxxxx\",oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"1628747273\",oauth_nonce=\"xxxxxxxx\",oauth_version=\"1.0\",oauth_signature=\"xxxxxxxx\"")
.header("Cookie", "NS_ROUTING_VERSION=LAGGING")
.body(JSONpayload).asString();
Any kind of help is appreciated. Thanks in Advance.

AWS Chime: How to sign an HTTP Request for Create Meeting API in spring boot?

I didn't find any useful way to generate the Signature V4 in java for signing an AWS Chime HttpRequest. I want to use 3 apis of Aws Chime (Create meeting, create attendee and delete meeting) inside my java code.
Can anyone help me please !
API Details:
Url: https://service.chime.aws.amazon.com/meetings
Body: { "ClientRequestToken": "AXEXAMPLE", "MediaRegion":
"us-east-2" }
Headers: "content-type", "application/json" "host",
"service.chime.aws.amazon.com" "x-amz-date", "20200526T094404Z"
"authorization", ?(Generated Signature)
API Key: JHDCHGEXAEXAMPLE Secret Key : 4sjfkkjffs/sfkkh/sfkj/example
private Response createMeeting() {
OkHttpClient client = new OkHttpClient();
Response response = null;
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\"ClientRequestToken\": \"AXEXAMPLE\",\n \"MediaRegion\": \"us-east-2\"\n}");
Request request = new Request.Builder()
.url("https://service.chime.aws.amazon.com/meetings")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("host", "service.chime.aws.amazon.com")
.addHeader("content-length", "68")
.addHeader("x-amz-date", getIsoDate())
.addHeader("authorization", "?????????") //To be replaced by generated signature
.addHeader("cache-control", "no-cache")
.build();
try {
response = client.newCall(request).execute();
System.out.println("ResponseMessage===========> " + response.message());
} catch (IOException e) {
System.out.println("Error===========> " + e.getMessage());
}
return response;
}
The error I am getting is: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

"Unacceptable content-type" when creating contact via Java client of sendinblue API

Really strange as I copy paste the code sample from the sendinblue API doc:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType,"\"updateEnabled\":false,\"email\":\"example#email.com\"}");
Request request = new Request.Builder()
.url("https://api.sendinblue.com/v3/contacts")
.post(body)
.addHeader("accept", "application/json")
.addHeader("content-type", "application/json")
.addHeader("api-key", "xxxxxxxxxxxxxxxxxx")
.build();
Response response = client.newCall(request).execute();
The response is:
response code is: 406
response message is: Not Acceptable
response body is: {"code":"not_acceptable","message":"Unacceptable content-type"}
I use this Java client:
<dependency>
<groupId>com.sendinblue</groupId>
<artifactId>sib-api-v3-sdk</artifactId>
<version>3.0.1</version>
</dependency>
You need to set the content-type in as JSON (application/json).

Unable to get MIME version of a Message using $value

I am unable to get MIME for a message using $value like specified in the documentation. How to get MIME?
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + accessToken)
.url("https://graph.microsoft.com/v1.0/me/messages/k4ZDQ5LTgzMTYtNGZhYS04ZTU3LWZhMjFmZmUzNmE1YwBGAAAAAABzUENX1K4kR6h6KAAA7ENoUb5BySZFX6KemUxNwAAAv_a5nAAA=/?value")
.build();
Response response = null;
String body;
try {
response = client.newCall(request).execute();
body = response.body().string();
Your URLs are incorrect, they're using /?value but should be using /$value ($ not ?). The $value is part of the path, not a query param:
https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value

Categories