I'm trying to register a user using okHttpClient 4.2.1 library and as a response I'm getting some garbage value
Respone is �������������V*.MNN-.V�JK�)N�Q�r�S���rR�SSR��K2��t�RK���ck�NY�<������
I used postman and the response is what I'm expecting. I don't understand why its not working in Android Studio.
{"result": {"OTP": 1113401845,"id": 143},"success": true,"message": "User Registered In Successfully"}
Here is the code I used
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
JSONObject postdata = new JSONObject();
try {
postdata.put("action", "registrationFirst");
postdata.put("User_name", "abcd");
postdata.put("password", "12345");
postdata.put("email", "aaaa3#a.com");
postdata.put("street", "qa");
postdata.put("Gender", "1");
postdata.put("Religion", "3");
postdata.put("caste", "Other");
postdata.put("Country", "UAE");
postdata.put("mobile", "0123456");
postdata.put("Locaion", "SHJ");
} catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(mediaType,postdata.toString());
Request request = new Request.Builder()
.url(myUrl)
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic aW5mb0Bhbm9vbnouY29tOjEyMTIxMg==")
.addHeader("User-Agent", "PostmanRuntime/7.20.1")
.addHeader("Accept", "application/json")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "cf631a82-2570-4c20-9c39-be0563240c67,f9cecf3d-2340-4fce-bb6f-c060c9f8894f")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Content-Length", "1278")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Log.d("Hola","Response is "+result);
}
} catch (Exception e) {
e.printStackTrace();
Log.d("Hola","Failed exception "+e);
}
You should remove the following line when building a request using Request.Builder:
addHeader("Accept-Encoding", "gzip, deflate")
When you specify your own Accept-Encoding value you're implying that you'd like to do your own decompression which is not the case for you.
It is possible that Android Studio do not decompress the response and show it to you compressed.
You might want to remove the header "Accept-Encoding", "gzip, deflate" for this to work properly.
Related
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());
}
I am using an OkHttp Client for my Webservice call, its working successfully with JAVA Main function and returning response.
Now, I want to call this client from Postman; but I dont know what URL Shall i call? Like in jersey we create a base URL from #PATH annotation in Spring we use #service. What shall be done in okhttp to create a base url to call? Please help.
public String soapCaller() throws IOException, JSONException {
Response response = null;
try {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=0146b9a4-7e99-4c83-8e9e-6049cfec55da&client_secret=cJ5nD0yJ4fV8eM1nU4tK2yI5wQ0lG6iE7cP5bD4lQ8dB0jS6pV&scope=ABLApis");
Request request = new Request.Builder()
.url("https://uat-api.abl.com/abl-api/uat/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("accept", "application/json")
.build();
response = client.newCall(request).execute();
}
catch(Exception e)
{
logger.info("e: " + e);
}
return response.toString();
}
}
with Jersey Annotations
#GET
#Path("/fundTransfer")
#Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String soapCaller() throws IOException, JSONException {
/////////////////////////////
Response response = null;
try {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=0146b9a4-7e99-4c83-8e9e-6049cfec55da&client_secret=cJ5nD0yJ4fV8eM1nU4tK2yI5wQ0lG6iE7cP5bD4lQ8dB0jS6pV&scope=ABLApis");
Request request = new Request.Builder()
.url("https://uat-api.abl.com/abl-api/uat/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("accept", "application/json")
.build();
response = client.newCall(request).execute();
}
catch(Exception e)
{
logger.info("e: " + e);
}
///////////////////////////////////////////
return response.toString();
}
}
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. :)
I am trying to emulate this request using RestTemplate in Spring Boot
curl -X POST
'https://my.craftar.net/api/v0/image/?api_key=123456789abcdefghijk123456789abcdefghijk'
-F "item=/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/"
-F "file=#back_cover.png"
Here's my code:
MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
params.add("item", "/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/");
final String filename=file.getOriginalFilename();
Resource contentsAsResource = new ByteArrayResource(file.getBytes()){
#Override
public String getFilename(){
return filename;
}
};
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(contentsAsResource, imageHeaders);
params.add("file", imageEntity);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> requestEntity =new HttpEntity<>(params,headers);
try {
ResponseEntity<String> responseEntity = restTemplate.exchange(url,HttpMethod.POST, requestEntity, String.class);
return responseEntity.getBody();
} catch (final HttpClientErrorException httpClientErrorException) {
return httpClientErrorException.getResponseBodyAsString();
} catch (Exception exception) {
return exception.getMessage();
}
The above request throws a HttpClientErrorException and this what the response body looks like
{"error": {"message": "Expected multipart/form-data; boundary=<..> content but got multipart/form-data;boundary=x6G0xWVxdZX4n8pYNU8ihGAnCg4Twj3DgMARYDs.", "code": "WRONG_CONTENT_TYPE"}}
I have also tried using FileSystemResource, but it throws the same exception. The problem probably lies in formatting the data in multipart content-type.
If it can help, this is the code template generated by Postman on a successful request using Okhttp.
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType,
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"item\"\r\n\r\n/api/v0/item/3d8dcdd1daa54bcfafd8d1c6a58249b5/\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"file\"; filename=\"times_logo.png\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
.url("https://my.craftar.net/api/v0/image/?api_key=c6d4750c7368806fab27294fba8d0f93d48e1e11")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "cf09a989-338e-4d68-8968-b30a43384e5f")
.build();
Response response = client.newCall(request).execute();
just add the Resource to params instead of creating a HttpEntity
params.add("file", contentsAsResource);
This code is working in os version 5.1 and above.
Access token is not generated in 5.0 os version and below.
// getting exception ssl layer connection closed by peer
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials");
Request request = new Request.Builder()
.url("https://uatapi.nationstrust.com:8243/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("authorization", "Basic N000SDNmU3RtVERuZmZ1R0JNMlBGR1FXdmtFYTpEQUFJcEprVUhjdXBwcEx4dkRPSkFYZjNwMmth")
.build();
try {
Response response = client.newCall(request).execute();
String test = response.body().string();
if (response.isSuccessful()) {
System.out.println(test);
} else {
System.out.println(response.code() +" : "+ response.message());
}
} catch (Exception e) {
e.printStackTrace();
}
//// here I have posted full code what I am trying to generate access token.