I keep connection failed error in my "onFailure" method - android

I'm using retrofit object to call my API but I keep getting
"java.net.ConnectException: Failed to connect to
api.backtory.com/185.105.185.244:443"
in my onFailure method
I have set the title using #Headers
I have added INTERNET permission to my manifests
I have added the gson-converter library and retrofit as well
public class RegisterUserController {
public void start(User user){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ChatRoomAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ChatRoomAPI chatRoomAPI = retrofit.create(ChatRoomAPI.class);
Call<User> call = chatRoomAPI.registerUser(user);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
Log.d("TAG" , "onResponse" + response.code());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.d("TAG" , "onFailure" + t.getCause()); //
}
});
}
}

Related

how to get response toast

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(uri)
.addConverterFactory(GsonConverterFactory.create())
.build();
ayapi api = retrofit.create(ayapi.class);
Call<model> call = api.adddata(namevalue,numbervalue,emailvalue,countryvalue,statevalue,cityvalue,pincodevalue,addressvalue,teams);
call.enqueue(new Callback<model>() {
#Override
public void onResponse(Call<model> call, Response<model> response) {
Toast.makeText(getApplicationContext(),"Inserted",Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(getApplicationContext(),home.class));
}
#Override
public void onFailure(Call<model> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});
You are running background work so you can not run toast like that
instead, you can do this:
ayapi api = retrofit.create(ayapi.class);
// define toast before calling background work
Toast toast =
Toast.makeText(getApplicationContext(),"Inserted",Toast.LENGTH_LONG);
Call<model> call = api.adddata(namevalue,numbervalue,emailvalue,countryvalue,statevalue,cityvalue,pincodevalue,addressvalue,teams);
call.enqueue(new Callback<model>() {
#Override
public void onResponse(Call<model> call, Response<model> response) {
//call toast here
toast.show();
finish();
startActivity(new Intent(getApplicationContext(),home.class));
}
#Override
public void onFailure(Call<model> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});
you can get Data from response.body() like this
Toast.makeText(getApplicationContext(),"Inserted" + response.body(),Toast.LENGTH_LONG).show();

Null Response fron "http" API using retrofit

I'm using retrofit to connect APIs. It is working fine when fetching data from https API but getting response "Null" and error body response "okhttp3.ResponseBody$1#174390c" when fetching data from http API.
Here is the Retrofit client class:
public static Retrofit getSClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
return retrofit;
}
Here is the Apiservice Class:
#GET("Mobile/OperatorFetch?")
Call<String>getOperatorDetails(#Query("apimember_id")String apiMemberId,
#Query("api_password")String apiPassword,
#Query("Mobileno")String mobileNumber);
Here is the ApiUtils Class:
public static ApiService getSApiService(){
return RetrofitClient.getSClient(PLAN_URL).create(ApiService.class);
}
Here is my network request method from Repository class:
private void fetchOperator(String apiId, String apiPassword, String mobile) {
ApiService apiService = ApiUtills.getSApiService();
apiService.getOperatorDetails(apiId, apiPassword, mobile)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful() && response.body() != null){
Log.e(TAG,"Operator fetch successful: " + response.body().toString());
}else {
Log.e(TAG,"Operator fetch failed: " + response.errorBody().toString());
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e(TAG,"Fetch operator failed" + t.getMessage());
}
});
}
Getting response from Post Man

How to list files from Github using Retrofit?

I'd like to create a Github repository that will contain only PDF files. For fetching PDF files I will use retrofit in a way described at this link:
https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server
So right now I just wanted to list all the files from one of my Android projects on Github. (right now it only contains one PDF file)
This is the implementation:
Network module:
private static final String BASE_URL = "https://github.com/username/repository/";
#Provides
#Singleton
Retrofit provideRetrofit(RxJavaCallAdapterFactory rxJavaCallAdapterFactory, Gson gsonConverterFactory) {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.addConverterFactory(GsonConverterFactory.create(gsonConverterFactory))
.build();
}
Retrofit service:
#Streaming
#GET(".")
Call<List<okhttp3.ResponseBody>> getFiles();
And inside my activity, I'm trying to fetch the files:
Call<List<okhttp3.ResponseBody>> call = retrofitService.getFiles();
call.enqueue(new Callback<List<okhttp3.ResponseBody>>() {
#Override
public void onResponse(#NonNull Call<List<okhttp3.ResponseBody>> call, #NonNull Response<List<okhttp3.ResponseBody>> response) {
if (response.body() != null) {
Toast.makeText(HomeScreenActivity.this, response.message(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<List<okhttp3.ResponseBody>> call, #NonNull Throwable t) {
Toast.makeText(HomeScreenActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
And when I run it, I get "Expected BEGIN_ARRAY but was STRING at line 7 column 1 path $" error in onFailure() method.
After that I tried this way (without List):
#Streaming
#GET(".")
Call<okhttp3.ResponseBody> getFiles();
And inside Activity:
Call<okhttp3.ResponseBody> call = retrofitService.getFiles();
call.enqueue(new Callback<okhttp3.ResponseBody>() {
#Override
public void onResponse(#NonNull Call<okhttp3.ResponseBody> call, #NonNull Response<okhttp3.ResponseBody> response) {
if (response.body() != null) {
Toast.makeText(HomeScreenActivity.this, response.message(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<okhttp3.ResponseBody> call, #NonNull Throwable t) {
Toast.makeText(HomeScreenActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
And the onResponse is called and the response is just this:
Response{
protocol=http/1.1,
code=200,
message=OK,
url=https: //github.com/username/repository/
}
Is this way of fetching PDF files even possible? If it is, can you tell me if something is not right with my implementation?

(2.0) Retrofit call inside a Retrofit call causes a Time out exception

I'm using Retrofit 2.0, the code below will log:
"insertListingImages, SocketOutOfTimeException:TimeOut timeout".
Why is it causing a timeout exception? how do I resolve it? The odd thing is that if the retrofit call, hi() isn't inside the retrofit call, insertListingImages() everything would work fine.
retrofit = new Retrofit.Builder()
.baseUrl("http://IP_ADRESS/")
.addConverterFactory(GsonConverterFactory.create())
.build().create(DatabaseInterface.class);
retrofit.insertListingImages(imageListingRequest).enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
Log.d("insertListingImages", "Success");
retrofit.hi().enqueue(new Callback<Void>(){
#Override
public void onResponse(Call<Void> call, Response<Void> response){
Log.d("hiTest", "Success");
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
Log.d("hiTest", "fail: " + t.toString() + " " + t.getMessage());
}
});
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
Log.d("insertListingImages", "fail: " + t.toString() + " " + t.getMessage());
}
});
You can change the connection time out and read timeout by this code. you have to set the custom client for the retrofit
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Here in the above code set the time out as 120 sec, you can change that according to your need
Needed to add below line in the build.gradle file
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Retrofit Can't return Data

i'm probebly doing something wrong,
i'm trying to figure out how to use retrofit, so for now i'm calling back just a general ResponseBody, and not yet parsing anything, (just a simple http get)
but retrofit can't get the data, what am i doing wrong ? >
my Retrofit API >
public interface retrofitApi {
String baseUrl = "http://localhost:3003/";
#GET("api/radBox/getDegrees")
Call<ResponseBody> getCallData();
class Factory {
private static retrofitApi service;
public static retrofitApi getInstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(retrofitApi.class);
return service;
} else {
return service;
}
}
}
}
and in my main Activity i put >
retrofitApi.Factory.getInstance().getCallData().enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("myLogs", "log: " + response);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("myLogs", "failed to Retrive Data");
}
});
I think your problem is caused by using "localhost". Looks like you are using your phone to connect to phone's 3003 port. Exchange the localhost to your Server IP to give a try.
I copy all your code in my retrofit project, I exchange the URL, everything is working well on my side, meaning your retrofit code has no problem.
Try use instead ResponseBody your model (for me it WeatherModel) which must will return from server.
Like this
String baseUrl = "http://api.openweathermap.org/";
#GET("data/2.5/weather")
Call<WeatherModel> getCallData(#Query("q") String q, #Query("lang") String lang,
#Query("appid") String appid);
and put in MainActivity like this
retrofitApi.Factory.getInstance()
.getCallData("Taganrog,ru", "ru", "bde41abf61e82b6209a544a5ea2ddb76")
.enqueue(new Callback<WeatherModel>() {
#Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
Log.d("myLogs", "log: " + response);
}
#Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
Log.d("myLogs", "log: " + "failed to Retrive Data");
}
});
It's works fine for me

Categories

Resources