Retrofit Can't return Data - android

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

Related

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

I keep connection failed error in my "onFailure" method

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

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?

How to get response from server as String ,Retrofit 1.9

I would like to handle my response from server , but I don't know how JSON (from server) its looks like. So I tried to display response as String , but I cant do it. Is it possible to display response as String? And then handle the response correctly. thanks
(Retrofit 1.9)
LoginService loginService = RetrofitClient.createService(LoginService.class);
loginService.searchOffer(getToken(), offerSearch, new Callback<String>() {
#Override
public void success(String offerSearchRequestResource, Response response) {
String responseFromSercer = response.getBody();
}
#Override
public void failure(RetrofitError error) {
}
});
change your response model to
JSONObject (from Gson)
then in your
public void success(...){response.body.toString();}
like this:
Call<JsonObject> call = YOUR_API_INTERFACE().YOUR_METHOD(YOUR_PARAMS);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, #NonNull Response<JsonObject> response) {
if(response.isSuccessful()) {
String responseFromSercer = response.body.toString();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
.....
}
});
If you are sure the request runs successfully and there is a response back...use
System.out.println(response.getBody());
i'd also suggest you add Logging Interceptors here so that you can get a detailed view of all your API calls

Retrofit call does executed but not trigger onResponse or onFailure

My call is executed but does not trigger the onResponse or onFailure method
The Json object that is returned has an image inside
This is the code in my interactor class
private ExamApi initiateRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(ExamApi.class);
}
public void getExamImage(String user, String token,String exId, String exDocId) {
if (examApi == null) initiateRetrofit();
Call<ResponseBody> call = examApi.getExamImage(user,token,exId,exDocId);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
listener.onImageSuccess(response.body());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//TODO ONFAILURE
//listener.onImageFailure();
listener.onFailure();
}
});
}
this is my examApi
#GET("mobile/getExamImage")
Call<ResponseBody> getExamImage(
#Query("user") String username,
#Query("token") String token,
#Query("exid") String exId,
#Query("edid") String exDocId
);
It is happening because you are making an asynchronous call on the retrofit. You are trying to capture the data even before the network call happens. This gives you a null result. Try Broadcasting the result using broadcast receiver or third party library like EventBus which will make your result available after the network call has happened.

Categories

Resources