What is API interface in Retrofit - android

While studying Retrofit Library I cae across API Interface I could not understand the Code/terms used inside it. Can anyone explain the lines of code??
public interface ApiInterface {
// For POST request
#FormUrlEncoded // annotation that used with POST type request
#POST("/demo/login.php") // specify the sub url for our base url
public void login(
#Field("user_email") String user_email,
#Field("user_pass") String user_pass, Callback<SignUpResponse> callback);
//user_email and user_pass are the post parameters and SignUpResponse is a POJO class which recieves the response of this API
// for GET request
#GET("/demo/countrylist.php") // specify the sub url for our base url
public void getVideoList(Callback<List<CountryResponse>> callback);
// CountryResponse is a POJO class which receives the response of this API
}
Thanks For any Response!!

Related

Is it possible to POST a package of json objects?

so I am building an applications that has to POST a json array with some information and also json object with user credentials which are going to be used for identification. Is is possible to POST some kind of package that contains json object array + object with user credentials? I am using Retrofit2.
So beside this Array list I would like to send Credentials with one POST request.
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body ArrayList<Post> post);
}
You have to do something like that
Define your API
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body PostRequest post);
}
Define your request
public class PostRequest {
final ArrayList<Post> posts;
final String credentials; // or anything you want
PostRequest(ArrayList<Post> posts, String credentials) {
this.posts = posts;
this.credentials = credentials;
}
}
You have to create a class for credentials just like you made a class for your array. Then you create another class named lets say "Request" and put credentials and your array in it like so:
public class Request {
final ArrayList<Post> posts;
final Credentials credentials;
//constructor, getters/setters
...
and then in your api do this:
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body Request post);
}

how to handle login api without token in interceptors using retrofit

I am using retrofit 2.0.2 for HTTP calls in which I have to send token in header for each API except login and signup. For this I have added this token into interceptors and contains information about the client but before login token is automatically added into interceptors. Is there any way to exclude token from interceptors for login and signup call
Check this link out, it contains a nice and clean way to handle this.
https://medium.com/kufar-tech/retrofit-tips-passing-custom-parameters-from-retrofits-request-to-okhttp-s-interceptor-989b8ceff07d
Briefly, you should create a custom annotation (for example named PublicAPI)
#Documented
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface PublicAPI { }
and add it to all services that won’t need authentication.
public interface LoginService {
#PublicAPI
#POST(value = "login")
#FormUrlEncoded
Call<Void> login(#Header("Authorization") final String credentials);
}
Retrofit’s RequestFactory creates an instance of Invocation object with service’s method and argumentList as parameters and sets it as Request tag. Therefore you can check whether your service annotated with PublicAPI or not within the interceptor and do wat you want based on it.
#Override
public #NonNull Response intercept(#NonNull final Chain chain) throws IOException {
Request request = chain.request();
Invocation invocation = request.tag(Invocation.class);
Annotation publicAPI = invocation.method().getAnnotation(PublicAPI.class);
if (publicAPI == null) {
//add access token
}
// rest
return response;
}
You can check the request path in the interceptor and do some stuff based on the request URL.
#Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if(originalRequest.url().encodedPath().equals("/some/login/path")){
// don't add token header
}else{
// add token header
}
}
or you may use the method provided at https://stackoverflow.com/a/41033670/1273657

Call webservice using Retrofit return invalid webservice result

I am using retrofit to retrieve login JSON result from server for that i need to post user name and password. I have tried this code but i get response saying invalid Web Service. but i get correct response using Rest.
My code is something like this,
MainActivity.java
String url = "http://***.***.in/***/******/*********/UserService.php?request=Verify_User_Credential";
//making object of RestAdapter
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
//Creating Rest Services
RestInterface restInterface = adapter.create(RestInterface.class);
//Calling method to get login report
restInterface.getLoginReport(username, password, new Callback<Model>()
{
#Override
public void success(final Model model, Response response) {
if (RetailConnectUtils.isSuccess(model.getStatus())) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// retrieve status and message from model and display
}
});
}
});
RestInterface::
#FormUrlEncoded
#POST("/GetData")
void getLoginReport(#Field("username")String uname,#Field("password")String password,Callback<Model> cb);
and POJO class model containing json converted values It contain method getStatus and getMessage...
Here what should i mention in #POST("******").. is that webservice method or default retrofit method?

Retrofit making empty body for request in Android

I am using Retrofit in android and GsonConverterFactory is converter.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxxxxxx.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
I want send POST request with body.
public class MasterRequest
{
}
public class User extends MasterRequest
{
#SerializedName("email")
public String email = null;
}
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body MasterRequest masterRequest);
path is the URL that append with base URL.
When ever I send child class("User") object in parent class reference(MasterRequest), then converter shown empty json; "{}".
But when I send User class object to below registerUser Method, then it working fine.
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body User user);
How can I send child class object in parent class instance to make request body?
That's how Gson works. The easiest way to serialize polymorphic objects is use RuntimeTypeAdapterFactory. You can find detailed tutorial here. Works great with Retrofit!

How to get response as String using retrofit without using GSON or any other library in android [duplicate]

This question already has answers here:
Unable to create call adapter for class example.Simple
(19 answers)
Closed 7 years ago.
I am trying to get response from the following Api :
https://api.github.com/users/username
But I don't know how to get response as String so that I can use the String to parse and get the JSONObject.
Retrofit version used:
retrofit:2.0.0-beta1
I have tried this until now:
public interface GitHubService {
#GET("/users/{user}")
public String listRepos(#Path("user") String user,Callback<String> callback);
}
retrieving :
GitHubService service = retrofit.create(GitHubService.class);
service.listRepos("username", new Callback<String>() {
#Override
public void onResponse(Response response) {
System.out.println(response.toString());
}
#Override
public void onFailure(Throwable t) {
}
});
exception:
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
* retrofit.ExecutorCallAdapterFactory
at retrofit.Utils.resolveCallAdapter(Utils.java:67)
at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)
Any help would be really appreciated.
** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
#GET("/users/{user}")
Call<String> listRepos(#Path("user") String user);
}
Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with #CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --
public interface GitHubService {
#GET("/users/{user}")
Call<ResponseBody> listRepos(#Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Categories

Resources