Okhttp3 Base URL for calling - java

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();
}
}

Related

How should I put code in Background Thread in Java?

I am using an API which uploads some data to the server, I am deploying this on android application.
I tested APIs using Postman and it works absolutely fine and generated code from postman
login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","abc#abc.com")
.addFormDataPart("password","E1234567")
.build();
Request request = new Request.Builder()
.url("192.168.1.51/auth/login")
.method("POST", body)
.addHeader("User-Agent", "Koala Admin")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
create user and upload photo
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("subject_type","1")
.addFormDataPart("name","jasim")
.addFormDataPart("start_time","1619496549")
.addFormDataPart("end_time","1619525349")
.addFormDataPart("photo","/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg")))
.build();
Request request = new Request.Builder()
.url("192.168.1.51/subject/file")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
Now I want to know that how can I put these code in AsyncTask class and make the necessary code in background.
You can call enqueue method instead of execute and it will work on the background thread:
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
// handle your response
}
#Override
public void onFailure(Call call, IOException e) {
// handle the failure
}
});

okHttpClient response gives garbage value

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.

Make a post request with okHttp

I make a post request using okHttp with the next code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
The server response with:
response
{
message: {
user: {
id: 12,
name: 'myName'
},
message: 'Usuario creado con éxito.',
code: 200
}
}
But the response that okHttp gives me is:
Response{protocol=http/1.1, code=200, message=OK, url=http://localhost:2222/api/users}
There isn´t a way to get what the server sends me with okHttp?
If the response is sent in the body you can get it with:
response.body().string();
You just had to look on the documentation
¡Salud!
What you are getting is the header of response object. you can access the body of response by:
response.body().string();
full code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
String responseBody = response.body().string();

How to generate access token on OS version 19 for payment gateway

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.

How to get HTTP Response Error Code Doing OkHttp Sync Requests

I'm using OkHttp with Retrofit to do synchronized requests. The problem is that OkHttp throws an exception. I can catch the exception in the interceptor instead, but the response is null.
I'd like to display messages to the user based on HTTP response codes.
Response<List<Employee>> owner = null;
Call<List<Employee>> webCall = getWebService().getDeviceOwner("tolower(LoginId) eq tolower(\'" + SharedData.AuthorizationUserName + "\')");
try {
owner = webCall.execute();
if(isHttpResponseSuccess(owner.code())) {
Employee employee = owner.body().get(0);
}
else {
Log.e(TAG_NAME, "GetDeviceOwner() call failed. Http code=" + owner.code() + "/nMessage=" + owner.message());
}
catch (Exception e) {
//Some type of network error. 401, etc? I have no clue.
Log.e(TAG_NAME, "GetDeviceOwner() exception=" + e);
}
Client Interceptor
_okHttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "Application/JSON")
.addHeader("Authorization", "Basic " + new String(Base64.encode((SharedData.AuthorizationUserName + ":" + SharedData.AuthorizationPassword).getBytes(), Base64.NO_WRAP)))
.removeHeader("charset")
.build();
okhttp3.Response response = chain.proceed(request);
Log.d(TAG_NAME, "Response code="+ response.code());
Log.d(TAG_NAME, "Response="+ response.toString());
return response;
}
}).addInterceptor(logging).build();
u can test this code , when the response isn't 2xx it will worked that u can get the code with e.getMessage();
_okHttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "Application/JSON")
.addHeader("Authorization", "Basic " + new String(Base64.encode((SharedData.AuthorizationUserName + ":" + SharedData.AuthorizationPassword).getBytes(), Base64.NO_WRAP)))
.removeHeader("charset")
.build();
okhttp3.Response response = chain.proceed(request);
if (response.code()/100!=2){
throw new IOException(response.code()+"");
}
Log.d(TAG_NAME, "Response code="+ response.code());
Log.d(TAG_NAME, "Response="+ response.toString());
return response;
}
}).addInterceptor(logging).build();
You can use HttpResponse class
HttpResponse httpResponse = client.newCall(request).execute();
httpResponse.getStatusLine().getStatusCode();
If you are using com.squareup.okhttp.Response then you can use the code() method.
Response httpResponse = client.newCall(request).execute();
httpResponse.code();

Categories