I have this Interface:
public interface InterfazAguaHttp {
#FormUrlEncoded
#POST("/")
Call<String> saveContador(#Field("contador") Long contador, Callback<String> callBack);
}
The rest of the code is this:
Retrofit builder = new Retrofit.Builder()
.baseUrl(ValoresGlobales.urlServlet)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfazAguaHttp interfaz = builder.create(InterfazAguaHttp.class);
Call<String> respuesta = interfaz.saveContador(93847597L, new Callback<String>() {
#Override
public void onResponse(Response<String> response, Retrofit retrofit) {
//Some logging
}
#Override
public void onFailure(Throwable t) {
//Some logging
}
});
This is all inside a try-catch block. In the catch, I am receiving this error:
Error: No Retrofit annotation found. (parameter #2) for method InterfazAguaHttp.saveContador
How could I get rid of this error, and still have my callback?
Thank you.
change your interface method to this
public interface InterfazAguaHttp {
#FormUrlEncoded
#POST("/")
Call<String> saveContador(#Field("contador") Long contador);
}
and the rest of the code like this
Retrofit builder = new Retrofit.Builder()
.baseUrl(ValoresGlobales.urlServlet)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfazAguaHttp interfaz = builder.create(InterfazAguaHttp.class);
Call<String> respuesta = interfaz.saveContador(93847597L);
respuesta.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response, Retrofit retrofit) {
//Some logging
}
#Override
public void onFailure(Throwable t) {
//Some logging
}
});
Link for reference
Related
I have two methods the first is named first() and the second is named second();
The first is a retrofit call :
private void first() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(apiConge.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
apiConge api = retrofit.create(apiConge.class);
Call<String> call = api.getCongeByUserId("Bearer " + token_data, id_data);
//finally performing the call
call.enqueue(new Callback<String>() { ...
And the second is also a retrofit call :
private void second() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(apiConge.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
apiConge api = retrofit.create(apiConge.class);
Call<String> call = api.getCongeByUserId("Bearer " + token_data, id_data);
//finally performing the call
call.enqueue(new Callback<String>() {
In my case i need to execute the second method when the first method call is completely finished.
You need to call second method when first call is done.
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response) {
second();
}
#Override
public void onFailure(Throwable t) {
}
});
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
This question may sound like a no-brainer but I'm having a hardtime.
I can do the post with retrofit 2 this way:
class RetrofitClient {
private static Retrofit retrofit = null;
static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Api service interface:
#POST("postsInit")
#FormUrlEncoded
Call<InitPost> postInit(
#Field("appVersion") String versionName,
#Field("appId") String applicationId,
);
And finally:
apiService.postInit(versionName, applicationId).enqueue(new Callback<InitPost>() {
#Override
public void onResponse(#NonNull Call<InitPost> call, #NonNull Response<InitPost> response) {
if (response.isSuccessful()) {
Timber.d("post submitted to API");
getInitResponse();
}
}
#Override
public void onFailure(#NonNull Call<InitPost> call, #NonNull Throwable t) {
if (call.isCanceled()) {
Timber.e("Request was aborted");
} else {
Timber.e("Unable to submit post to API.");
}
}
});
How can I convert this to RxJava 2 ? I've already implemented the converter factory but there is no info on the internet for using rxJava 2 and retrofit 2 together.
Converting your call in RxJava code:-
apiService.postInit(versionName, applicationId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io())
.subscribe(new Subscriber<InitPost>() {
#Override
public void onSubscribe(Subscription s) {
}
#Override
public void onNext(InitPost initPost) {
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
}
});
}
Post service interface:
#POST("postsInit")
#FormUrlEncoded
Observable<InitPost> postInit(
#Field("appVersion") String versionName,
#Field("appId") String applicationId,
);
I am creating a simple log-in/register app, consuming predefined JSON-structured data. So far I have created the GET endpoint (using retrofit)
public interface RetrofitGet {
#GET("----")
Call<User> getUserDetails();
}
EDIT: the POST endPoint:
#POST("----")
Call<User> postUserDetails();
Then I have a method, taking the entered JSON-like data and set the data as text of 2 of the fields:
private void getUser() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitGet service = retrofit.create(RetrofitGet.class);
Call<User> call = service.getUserDetails();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
try {
input_email.setText(response.body().getEmail());
input_pass.setText(response.body().getPassword());
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
What I am trying to do now is to define the POST endpoint, in order to be able the data to be generated from the app (to be taken from the register form), posted on the server, and then handled in the login.
EDIT:
The method, consuming the POST endpoint so far:
private void postUser() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitPost service = retrofit.create(RetrofitPost.class);
Call<User> call = service.postUserDetails();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
try {
emailRegister.getText().toString();
passRegister.getText().toString();
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
So, I have the data, entered by the user on Register, but I don't see it stored in the server and cannot handle it in the Login part.
Any help would be appreciated,
Thanks!
#POST("----")
Call<CommonBean> comment(#Body PostComment comment);
and the PostComment:
public class PostComment {
private int pcOrdersId;
private int pcStar;
private String pcComment;
public PostComment(int pcOrdersId, int pcStar, String pcComment) {
this.pcOrdersId = pcOrdersId;
this.pcStar = pcStar;
this.pcComment = pcComment;
}
}
others on different with 'GET'
I have an issue trying to use Okhttp with retrofit. I seem not to understand what I am doing wrong.
It gives showing up error: 'Anonymous class derived from Callback' must either be declared abstract or implement abstract method 'onResponse(Response<T>, Retrofit)' in 'Callback'
In my MainActivity I have this:
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Content-Type", "application/json")
.header("Authorization","authorization_code")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
TestInterface service = retrofit.create(TestInterface.class);
Call<TestData> call = service.getPost();
/* It keeps pointing at this line below:
'Callback' must either be declared abstract" */
call.enqueue(new Callback<TestData>() {
#Override
public void onResponse(Response<TestData> response, Retrofit retrofit) {
// Get result Repo from response.body()
// response.isSuccess() is true if the response code is 2xx
int statusCode = response.code();
if (response.isSuccess()) {
System.out.println("Success: ");
} else {
}
}
#Override
public void onFailure(Throwable t) {
System.out.println("failed: "+t);
}
});
In my TestData Interface,I have this
public interface TestInterface {
#POST("/paths_to_web_directory")
Call<TestData>
getPost();
}
This is the way i see it done in other examples, So maybe i'm implementing it the wrong way. Kindly correct me. Thanks
The retrofit github project has a sample with a different method signature. Try this:
call.enqueue(new Callback<TestData>() {
#Override public void onResponse(Call<TestData> call, Response<TestData> response) {
}
#Override public void onFailure(Call<TestData> call, Throwable t) {
}
});