I am new in retrofit. I completed all setup.
I add this gradle in build.gradle file
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
My Interface is like this:
public interface ILoginInterface {
String BASE_URL= "MY_BASE_URL/";
#POST("MY/API")
Call<LoginResponseEntity> startLogin(#Body JSONObject jsonObject);
class Factory{
private static ILoginInterface instance;
public static ILoginInterface getInstance(){
if(instance==null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
instance = retrofit.create(ILoginInterface.class);
}
return instance;
}
}
}
My Calling procedure is like this:
ILoginInterface.Factory.getInstance().startLogin(jsonObject).enqueue(new Callback<LoginResponseEntity>() {
#Override
public void onResponse(Call<LoginResponseEntity> call, retrofit2.Response<LoginResponseEntity> response) {
Log.d("MS",response.body().fullName);
}
#Override
public void onFailure(Call<LoginResponseEntity> call, Throwable t) {
Log.d("MS",t.getMessage());
}
});
Here jsonObject is like this:
{"user_name":"sajedul Karim", "password":"123456"}
Here it seems everything is ok but i didn't getting proper response.
I found a solution. it is here . Does anybody have proper solution like Volley JsonObjectRequest
May be you are importing
import org.json.JSONObject;
you should use
import com.google.gson.JsonObject;
Then you will get it's value.
Related
I'm a beginner in Android programming. just started.
Now I'm trying to communicate between Android and Tomcat server using retrofit.
but whenever I click login button, this error keeps me crazy.
java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1)
Here are my errors..
java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1)
for method NetworkService.postLogin
at com.example.ab.MainActivity.networkServiceModule(MainActivity.java:68)
at com.example.ab.MainActivity$1.onClick(MainActivity.java:50)
I added these in gradle
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
Interface :
public interface NetworkService {
#POST("/Attendance/login.jsp")
Call<PostJson> postLogin(PostJson postJson);
}
some part of MainActivity :
ApplicationController application = ApplicationController.getInstance();
application.buildNetworkService("xxx.xxx.xxx.xxx",8080);
networkService = ApplicationController.getInstance().getNetworkService();
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ID = id.getText().toString();
String Pwd = password.getText().toString();
networkServiceModule(ID,Pwd); //this is line 50.
}
});
public void networkServiceModule(String ID, String Pwd){
Log.d("networkServiceModule","ID : "+ID);
Log.d("networkServiceModule","PW : "+Pwd);
Call<PostJson> thumbnailCall = networkService.postLogin(new PostJson(ID,Pwd)); //this is line 68.
thumbnailCall.enqueue(new Callback<PostJson>() {
#Override
public void onResponse(Response<PostJson> response, Retrofit retrofit) {
if(response.isSuccess()) {
String resultCode = response.body().getResult_code().toString();
Toast.makeText(getBaseContext(), "Login : " + resultCode, Toast.LENGTH_SHORT).show();
} else {
int statusCode = response.code();
Log.d("networkServiceModule", "response Code : "+statusCode);
}
}
ApplicationController :
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class ApplicationController extends Application {
private static ApplicationController instance;
public static ApplicationController getInstance() {
return instance;
}
#Override
public void onCreate() {
super.onCreate();
ApplicationController.instance = this;
}
private NetworkService networkService;
public NetworkService getNetworkService() {
return networkService;
}
private String baseUrl;
public void buildNetworkService(String ip, int port) {
synchronized (ApplicationController.class) {
baseUrl = String.format("http://%s:%d", ip, port);
Gson gson = new GsonBuilder()
.create();
GsonConverterFactory factory = GsonConverterFactory.create(gson);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(factory)
.build();
networkService = retrofit.create(NetworkService.class);
}
}
}
I've kept trying to apply some solutions that I got from StackOverflow, but failed to find one for mine..
This is my first question on StackOverFlow, sorry for codes looking ugly.
You forgot to annotate the retrofit method parameter. Try the following
#POST("/Attendance/login.jsp")
Call<PostJson> postLogin(#Body PostJson postJson);
the problem is with PostJson postJson, every former parameter has to be associated with a retrofit annotation. In your case that should be the body of your post request.
Call<PostJson> postLogin(#Body PostJson postJson);
Though this answer is not specifically related to question, I found myself here while solving the issue. I solved it, therefore sharing.
I was trying to use retrofit along with coroutines and getting error Retrofit Error : No Retrofit annotation found. (parameter #2) , even though there was no parameter #2.
/**
* Suspend function to get media of the day for the day when this function is called.
* Will return a Media object in the response.
*/
#GET("planetary/apod")
suspend fun getTodaysMedia(#Query("api_key") apiKey: String): Media
Solved this by upgrading the retrofit version: version_retrofit = "2.9.0"
You forgot to annotate the retrofit method's parameters #Body like
#POST("/Attendance/login.jsp")
Call<PostJson> postLogin(#Body PostJson postJson);
I'm using retrofit 2 to make api call to my server but it get stucked when trying to make api call. This is my code
public interface GOTApi {
#GET("characters.json")
Call<GOTCharacterResponse> getCharacters();
}
Intermediate class to get the data
public class GOTCharacterResponse {
List<GOTCharacter> characters;
}
My class to make api call
public class GOTService {
public static final String BASE_URL = "https://project-8424324399725905479.firebaseio.com/";
public static GOTApi getGOTApi(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(GOTApi.class);
}
public static void getCharacters(){
getGOTApi().getCharacters().enqueue(new Callback<GOTCharacterResponse>() {
#Override
public void onResponse(Call<GOTCharacterResponse> call, Response<GOTCharacterResponse> response) {
if(response.isSuccessful()){
}
}
#Override
public void onFailure(Call<GOTCharacterResponse> call, Throwable t) {
int a = 0;
}
});
}
}
These are the libraries I'm using
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
It always get stucked in the getCharacters() method. Of course I have internet permission set in Mainfest.
You may try using Retrofit2 with RxJava, it is more convenient.
public Retrofit providedRetrofit(OkHttpClient okHttpClient){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit;
}
Your API interface will look like
public interface Api {
#GET("api/service/schedule/{filial}")
Observable<Response<GOTCharacter>> getSchedule(#Path("some_param") String param);
}
You also need to parse response from JSON. You didn't provided
GOTCharacter class, but you can create code from json response by using
http://www.jsonschema2pojo.org/ service
I think you are implementing wrong onResponse() OR Callback(), because I am using Retrofit 2 too, in which onResponse() looks like this:
#Override
public void onResponse(Response<ListJsonResponseRestaurant> response, Retrofit retrofit) {
...
...
}
I am using Retrofit 2.0 library in my android application by adding it into build.gradle file
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
related code is given below
ApiInterface.java
public interface ApiInterface {
#GET("contacts/")
Call<ContactsModel> getContactsList();
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "http://myexamplebaseurl/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ContactsModel> call = apiService.getContactsList();
call.enqueue(new Callback<ContactsModel>() {
#Override
public void onResponse(Call<ContactsModel> call, Response<ContactsModel> response) {
if(response.isSuccessful()){
/*here is my data handling*/
}
}
#Override
public void onFailure(Call<ContactsModel> call, Throwable t) {
/*It is the request failure case,
I want to differentiate Request timeout, no internet connection and any other reason behind the request failure
*/
}
});
if we get status code as 4xx or 5xx even though onResponse() will called, so there we need handle that condition also.
Here my question is, How to differentiate reason for request failure i.e onFailure() by using Retrofit 2.0 in Android?
Here my question is, How to differentiate reason for request failure
by using Retrofit 2.0 in Android?
if you have a 4xx or 5xx error, onResponse is still called. There you have to check the response code of the code to check if everything was fine. E.g
if (response.code() < 400) {
in case of No Network connection, onFailure is called. There you could check the instance of the throwable. Typically an IOException
I want to use GsonConvertFactory.create()
but when i try to import
import retrofit.GsonConverterFactory;
i don't find the package in Retrofit 2
Add compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' to your dependencies.
Fast Solution
you can change you retrofit dependency to
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
but be aware the retrofit 2 work a bit differently about retrofit
asynch requests you call
for example
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
client = retrofit.create(YOUR_INTERFACE.class);
Call<JsonObject> call = client.getNews();
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Response<JsonObject> response
, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
}
});
for more detail you can check
http://www.vogella.com/tutorials/Retrofit/article.html
http://inthecheesefactory.com/blog/retrofit-2.0/en
It seems the library has been moved. The 2.0.0-beta4 didn't work for me. 2.3.0 does.
I'm writting a retrofit demo.
I have to use "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code" to get code.
when writing rest, I do it like this:
public interface WXService {
#GET("/access_token?grant_type=authorization_code")
Observable<AccessTokenModel> getAccessToken(#Query("appid") String appId,
#Query("secret") String secretId,
#Query("code") String code);
}
public class WXRest {
private static final String WXBaseUrl = "https://api.weixin.qq.com/sns/oauth2/";
private WXService mWXService;
public WXRest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WXBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
mWXService = retrofit.create(WXService.class);
}
public void getAccessToken(String code) {
mWXService.getAccessToken(Constants.APP_ID, Constants.SECRET_ID, code)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<AccessTokenModel>() {
#Override
public void call(AccessTokenModel accessTokenModel) {
Log.e("WX", "accessToken:" + accessTokenModel.accessToken);
}
});
}
}
but I got an error:
java.lang.IllegalArgumentException: Unable to create call adapter for
rx.Observable
I think it's the way i transform the url wrong.But I don't know how to fix it.
i think you should include adapter-rxjava lib to your gradle dependencies.
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
and then add call adapter factory to your retrofit builder
public WXRest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WXBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mWXService = retrofit.create(WXService.class);
}