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());
}
Related
I call below URL using cURL
curl 'http://username:password#192.168.1.108/merlin/Login.cgi'
and I get proper response
{ "Session" : "0xb3e01810", "result" : { "message" : "OK", "num" : 200 } }
I get the same response from browser (directly open link), postman and even with NodeJs,
but I get response code 401 when send GET_Request to this url using okhttp in java
my java code with okhttp is
Request request = new Request.Builder()
.url("http://username:password#192.168.1.108/merlin/Login.cgi")
.build();
try {
com.squareup.okhttp.Response response = client.newCall(request).execute();
System.out.println(response.code());
} catch (IOException e) {
e.printStackTrace();
}
Use basic authentication. Having username and password in the url, separated with :, is the same as basic authentication. I tested and it's ok. my snippet is:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://192.168.1.108/merlin/Login.cgi")
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes()))
.get().build();
try (Response response = client.newCall(request).execute()) {
assert response.body() != null;
String res = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
I'm trying to upload a file to a REST-Service via okhttp3 (3.9.0).
It does not work and I got the error: ** code=422, message=Unprocessable Entity**
but I can't find my error ...
Here is my code:
private void test_OK_HTTP() {
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
File f = new File("C:\\history48.png");
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("DocumentName", "file.png")
.addFormDataPart("FK_Person", "1d64b9cc-d405-47c4-9adb-ef276c391ae0&")
.addFormDataPart("FK_FileManagerFormKey", "33")
.addFormDataPart("SystemFileType", "368")
.addFormDataPart("Subject", "test")
.addFormDataPart("SubjectDate", "2022-02-24")
.addFormDataPart("DocumentContent", "file.png", RequestBody.create(MediaType.parse("image/png"), f))
.build();
Request request = new Request.Builder()
.url("http://myurlthatworksfine/RestServiceTest/AddNewDocument")
.addHeader("api-version", "v1")
.addHeader("Authorization", basicAuth)
.post(requestBody)
.build();
System.out.println("Request: "+request.body().toString());
try {
Response response = client.newCall(request).execute();
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error: "+e);
}
}
Has any one any idea what I'm doing wrong?
Thanks.
I had a simple error in my test-id ... it works now ... :)
WRONG:
.addFormDataPart("FK_Person", "1d64b9cc-d405-47c4-9adb-ef276c391ae0&")
OK:
.addFormDataPart("FK_Person", "1d64b9cc-d405-47c4-9adb-ef276c391ae0")
I tried this with openid-connect, and it is working. I want same thing for SAML. FYI, I'm doing demo with Keycloak. So I already changed protocol from openid-connet to SAML inside Keycloak console/dashboard.
Code:
#Override
protected Boolean doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
/*For openid-connect*/
//RequestBody body = RequestBody.create(mediaType, "client_id=lifetrenz-client-1&username=test&password=test#123&grant_type=password&client_secret=c89b1eed-136d-445f-bfb0-e7e2bdac89ee");
/*For SAML*/
RequestBody body = RequestBody.create(mediaType, "client_id=lifetrenz-client-1&username=test&password=test#123&grant_type=password");
/*URL is changing manually accoridng to protocol*/
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/auth/realms/Lifetrenz/protocol/saml/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = client.newCall(request).execute();
data = "CODE: " + response.code() + "\n" + "MESSAGE: " + response.message() + "\n" + "BODY: " + response.body().string();
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
Please guide me. And please answer in Java instead of Kotlin.
You can't just change the protocol to SAML and then send OpenID Connect parameters.
Here's an example of a SAML request. The parameters are completely different.
And you can't use REST API. SAML uses browser redirects.
Not a Keycloak expert but your application needs a client-side SAML stack.
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.
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. :)