I am writing my first code in Retrofit 1.9
version. I tried to follow several blog but not able to understand very basic problem. So far, I have created Model
class using jsonschema2pojo
, RestAdapter
class.
Here is my model class:
@Generated("org.jsonschema2pojo")
public class GmailOauth {
@Expose
private String createdAt;
@Expose
private String objectId;
@Expose
private String sessionToken;
@Expose
private String username;
..... Getter and Setter methods...
I have created above model
class using Jsonschema2pojo
. So, my response JSON is very understandable.
public class RestApiAdapter {
public static final String BASE_URL = "http://testingserver.com:8081";
public RestAdapter providesRestAdapter(Gson gson) {
return new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
}
}
interface GmailSignInAPI {
@POST("/signWithGmail")
void GmailOauthLogin(@Body GmailOauth user, Callback<GmailOauth> cb);
}
Now, I am confused how to write Retrofit
client to pass following
form-data post parameter in efficient way?
accessToken (String value)
userID (String value)
How about if I want to pass custom object in a post request and save the response of request in same object? Is this good way to do it?
I think for the api portion of Retrofit I would put
@FormUrlEncoded
@Post("/path/to/whatever")
void authenticateWithSomeCredentials(@Field("username") String userName, Callback<Object> reponse
Then I would call it like this:
public void authenticateWithSomeCredentials(username), new Callback<Object>() {
@Override
public void success(Object object, Response response) {
// Do something
}
@Override
public void failure(RetrofitError error) {
// Do something
}
}
To add the token to every call you could add an interceptor:
public class YourAuthInterceptor implements interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
request = chain.request().newBuilder()
.addHeader("token"), tokenVariable)
.build();
return chain.proceed(request);
}
}
this will add a "token" to every call you make with retrofit
so then when you build your api you build it like this
YourApi api = new RestAdapter.Builder()
.setEndpoint(url)
.setRequestInterceptor(new YourAuthInterceptor())
.build()
.create(YourApi.class);
I hope this makes sense as I am typing it rather quickly. If you have any questions please let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With