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?
Related
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()); //
}
});
}
}
I am having problem while calling two different APIs. There is no problem while calling first API using retrofit but when it reaches second retrofit call, there occurs error. Following is my code.
//for first retrofit call:
apiInterface = ApiClient.getApiClient().create(LekhaDrillInterface.class);
Call<LekhaDrillModel> call = apiInterface.getData(id, memberId);
call.enqueue(new Callback<LekhaDrillModel>() {
#Override
public void onResponse(Call<LekhaDrillModel> call, Response<LekhaDrillModel> response) {
posts = Collections.singletonList(response.body());
adapter = new LekhaBolpatraDrillAdapter(posts, getApplicationContext());
rvLekhaDrill.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<LekhaDrillModel> call, Throwable t) {
Log.e("error", t.getMessage());
}
});
here is no error and data is set in adapter
//2nd retrofit call
private void callRetrofitListData(){
pariyojanaInterfaces = ApiClient.getApiClient().create(PariyojanaInterface.class);
Log.e("memberIDIDID", String.valueOf(memberId));
Call <Data> call1 = pariyojanaInterfaces.getData(memberId);
call1.enqueue(new Callback<Data>() {
#Override
public void onResponse(Call<Data> call, Response<Data> response) {
datas = (List<Data>) response.body();
if (response.body()!=null){
Log.d("jchhec","chekc");
}
itemListAdapter = new ItemListAdapter(getApplicationContext(), datas);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rv.setAdapter(itemListAdapter);
}
#Override
public void onFailure(Call<Data> call1, Throwable t) {
Log.e("error", t.getMessage());
}
});
}
the error is in the line
Call <Data> call1 = pariyojanaInterfaces.getData(memberId);
and the error is
Unable to create call adapter for interface retrofit2.Call for method PariyojanaInterface.getData
PariyojanaInterface.java
public interface PariyojanaInterface { #POST("projectBudget/pariyojanaListForMobile") Call getData(#Query("memberId") int memberId);
Can anybody please help me fix this problem?
First you must change PariyojanaInterface.java to
public interface PariyojanaInterface {
#POST("projectBudget/pariyojanaListForMobile") Call<List<Data>> getData(#Query("memberId") int memberId);
}
I Dont khow what your Data is, so you must replace List<Data> with List<yourData>
And you must change new Callback<Data> To new Callback<List<Data>
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?
this is my interface:
public interface ApiService {
#GET("uploads/{file_name}")
Call<ServerResponse> downloadFile(#Path("file_name") String fileName);
}
and this is my downloading code :
private void downloadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
ApiService getResponse = ApiClient.getClient().create(ApiService.class);
Call<ServerResponse> call = getResponse.downloadFile(file.getName());
call.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
}
});
}
Probably, you are referring that the method "enqueue()" is called, but it's not the onResponse one.
Please wait some time (a minute is fine) and make sure that onResponse nor onFailure are called.
If you want more info, you can use the HTTP logging interceptor
#POST("uploads/{file_name}")
Observable<Document> getDocumentsList(#Path("file_name") String fileName);
and the code webservice call should be
Observable<Document> listObservable = mApiService.getDocumentsList(path);
subscribe(listObservable, new Consumer<Document>() {
#Override
public void accept(Document resourceDtos) throws Exception {
fillDocs(resourceDtos.getData());
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
fillDocs(throwable.getMessage());
}
});
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
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