How to get HTTP Response Error Code Doing OkHttp Sync Requests - java

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

Related

Uploading File with okhttp 3.9.0 to REST is giving Error code=422, message=Uprocessable Entity

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")

Okhttp3 Base URL for calling

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

How to Post multiple image using OkHttpClient in android studio java?

I need to send multiple files from android app
I have already succeeded sending the single file but I need to send multiple
my request body
RequestBody form = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("user_id", user_id)
.addFormDataPart("title", title)
.addFormDataPart("description", description)
.addFormDataPart("price", price)
.addFormDataPart("offer_price", offer_price)
.addFormDataPart("amenities", amenities)
.addFormDataPart("type", type)
.addFormDataPart("status", "1")
.addFormDataPart("file", user_id + ".JPG", RequestBody.create(MEDIA_TYPE_PNG, bytarray))
.addFormDataPart("file1", user_id + "1.JPG", RequestBody.create(MEDIA_TYPE_PNG, bytarray1))
.addFormDataPart("file2", user_id + "2.JPG", RequestBody.create(MEDIA_TYPE_PNG, bytarray2))
.build();
post url
String url = path.URL + path.CREATE_POST_API;
Request request = new Request.Builder()
.url(url)
.post(form)
.build();
Okhttp execute
try (Response response = okHttpClient.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// System.out.println(response.body().string());
Log.d("runPost: ", response.body().string());
} catch (IOException e) {
e.printStackTrace();
}

Retrofit: Making Web Requests to Internal APIs

I want to make a request to my organisation api's. The request contains Headers, UserName, Password, & Cookie for session management.
Below is the actual code (in HttpClient) which I want to rewrite using Retrofit. I have heard that HttpClient libraries have been deprecated or someting so have opted Retrofit. I expect the response with 200 status code.
public static CookieStore cookingStore = new BasicCookieStore();
public static HttpContext context = new BasicHttpContext();
public String getAuth(String login,String password) {
String resp = null;
try {
String url = DOMAIN+"myxyzapi/myanything";
context.setAttribute(HttpClientContext.COOKIE_STORE, cookingStore);
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String log = URLEncoder.encode(login, "UTF-8");
String pass = URLEncoder.encode(password, "UTF-8");
String json = "username="+log+"&password="+pass+"&maintain=true&finish=Go";
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post,context);
resp = EntityUtils.toString(response.getEntity());
accountPoller();
} catch(Exception a) {
log.info("Exception in authentication api:"+a.getMessage().toString());
}
return resp;
}
Below is my code where I can't figure out how to pass the context with request. HttpResponse response = client.execute(post,**context**); using retrofit.
I don't even know if I have made my retrofit request right.
try {
String log = URLEncoder.encode(login, "UTF-8");
String pass = URLEncoder.encode(password, "UTF-8");
RequestBody formBody = new FormBody.Builder()
.add("username=", xyz)
.add("password=", mypass)
.add("&maintain=", "true")
.add("finish=", "Go")
.build();
String url = www.xyz.com+"myxyzapi/myanything";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(formBody).addHeader("Content-Type", "application/x-www-form-urlencoded").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
final String myresp = response.body().string();
}
}
});
} catch(Exception a) {
a.getMessage();
}
You have to catch exception and use this class.
retrofit2.HttpException
retrofit2
Class HttpException
int
code()
HTTP status code.
String
message()
HTTP status message.
Response
response()
The full HTTP response.

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.

Categories