I am trying to learn about Retrofit since it seems to take care of a lot of the issues I am currently having with JSON requests and handling.
first and foremost, I understand that the methods we use are defined inside of interfaces, while making simple requests to obtain data it is quite simple to specify what is to be retrieved from the url as well as all the necessary endpoints based on the famous github example.
So if we are retrieving information form the github api, we would first create all the necessary pojo models and such and then define the interface as:
public interface GithubService {
#GET("users/{username}")
Observable<Github>getGithHubUser(#Path("username")String userName);
}
From that on the main activity we would have something like:
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.github.com/")
.build();
GithubService githubService = retrofit.create(GithubService.class);
Observable<Github> githubUser = githubService.getGithHubUser("usersName");
githubUser.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.map(user -> "Github Username: " + user.getName() + "\nUrl:" +user.getUrl() + "\nfollowing: "+ user.getHireable())
.subscribe(userInfo -> Log.d("Output", userInfo));
My question here would be how to send JSON information if the url requires something like this:
"data={\"process\":\"procesNumber\", \"phone\":\"123456\"}"
Basically, in order to get any response form the server I have been doing this using simple okhttp:
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(CREATE_MEDIA_TYPE, "data={\"process\":\"procesNumber\", \"phone\":\"123456\"}");
String ALLWAYS_API = "http://something something bla bla";
Request request = new Request.Builder()
.url("https://blablabla")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
... etc etc etc
}
To my understanding, even I need to create a pojo class that represents the data that needs to be sent to retrofit, something along the lines of:
public class DataRequest {
final String proces;
final String phone;
DataRequest(String process, String phone) {
this.process = process;
this.phone = phone;
}
}
Which would comply to the information being sent to the request, but how would I actually parse that to the interface implementation?
interface DataService {
#Post(not a clue what to place here)
DataRequest postJson(#Body how?)
}
And how would I actually add that to the retrofit builder? The examples that I am using come from different forums on the web as well as other questions asked by other users, this one in particular helped a lot in understanding a couple of things: How to POST raw whole JSON in the body of a Retrofit request? but I still don't understand where everything goes and some of the other questions and examples are far too complex for what I need to do.
Ok, so in order to leave an answer here for anyone trying to do this. By default, retrofit comes with many utilities which handle the passing of data as JSON, but in this case what I am passing is a string that looks like json inside of a tag called data......I know..
But in order to answer this for the people facing similar issues, in order to pass in the string we need to import a scalar convertor much in the same way that we need to import a gson converter to work with our retrofit services:
compile 'com.squareup.retrofit2:converter-scalars:2.0.2'
After that, our service can be handled as:
public interface CreateService {
#Headers({ "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"})
#POST("your/post/path/goes/here")
Call<String> getStringScalar(#Body String body);
}
I write my service generators in a separate file, in this case, the whole thing can be used in this way:
public class ServiceGeneratorWithScalarConvertor {
private static final String API_BASE_URL = "your/base/url/goes/here";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// basically, this code is the same as the one from before with the added instance of creating and making use of the scalar converter factory.....scratch that i took it off
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
}
From there, we can access the results with this particular method(i am using this method inside my main activity:
public void retroFitCreateAPIExample() {
CreateService service = ServiceGeneratorWithScalarConvertor.createService(CreateService.class);
String body = "data={\"process\":\"process1\",\"phone\":\"12345\"}";
Call<String> call = service.getStringScalar(body);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Log.d("Response Body>>>>>", response.body());
createR = new Gson().fromJson(response.body().toString(), CreateModels.class);
Log.d("CREATED RESPONSE",createR.getCreate().getStops().get(0).getCity());
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
The instance is this passed to the service generator that uses scalar convertors, the body of the post request is saved as a simple string(as it was specified in the interface) and we can do with the response whatever we want.
Related
I am trying to make a POST request using the Micronaut framework with Java. I have created a 'client' class that is called and makes the request. Here is the code:
#Singleton
public class ApiClient {
private final HttpClient httpClient;
private final URI uri;
public ApiClient(#Client(URL) HttpClient httpClient) {
this.httpClient = httpClient;
uri = UriBuilder.of(API_URL).build();
}
Mono<List<ApiResponse>> fetchResponse() {
HttpRequest<?> request = HttpRequest.POST(uri, BODY)
.header("Authorization", API_KEY);
return Mono.from(httpClient.retrieve(request, Argument.listOf(ApiResponse.class)));
}
}
My problem is that I have no idea what the response from API is. As far as I can tell, the call is made. But because the data returns in a Flux object, I can't interrogate the object to find the response. My suspicion is that the POJO I'm trying to store the response in isn't working. I can't tell if this is the case though.
You need to subscribe to the publisher to actually make the request and get a response. There are several subscribe methods depending on what you want to do
I'm using the Java SDK to start a voice call using something similar to
Call.creator(to, from, callbackAddress)
I provide a URL (callbackAddress) that will receive the callback once the call is connected. Is there some way to configure this callback to be in JSON instead of "application/x-www-form-urlencoded; charset=UTF-8"?
The reason why I'm trying to do that is because I'm using Spring and ultimately I'm trying to receive the request parameters already in a deserialized Pojo in my RestController (parameter body in my example below), which is standard in SpringMVC. This is much easier to do using jackson, which requires a JSON request body
As a secondary question, is there a class in the Twilio SDK that encapsulates all the parameters in a request already or I would have to create such class?
Here is a dummy rest controller to illustrate what I'm trying to do. Note that the logic there with the "out of city" error is just a silly demo to show why I need to access the request parameters. All the samples I found about callbacks always ignored the request parameters and returned a static TwiML
#RestController
#RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TwilioCallbackController {
#PostMapping
public String handleCallback(RequestBody body /*this arg should have all request params*/) {
log.info("received callback for callId {}", body.getCallSid())
if (!body.toCity().equals("my-city")) {
throw new Exception("outside of city");
}
return createTwiML(body);
}
}
Twilio developer evangelist here.
There is no way to have Twilio send you the webhook in JSON format, it will be sent as form encoded parameters. However, there shouldn't be an issue having Spring parse them.
As this answer suggests, you can create a class that will parse the parameters into it by creating a class with getters and setters for each of the parameters.
So, for example, you could create the following class:
public class TwilioWebhook {
private String CallSid;
private String From;
public String getCallSid() {
return CallSid;
}
public void setText(String CallSid) {
this.CallSid = CallSid;
}
}
Which you could then use to parse the CallSid from the incoming webhook parameters like:
#RestController
#RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public class TwilioCallbackController {
#PostMapping
public String handleCallback(TwilioWebhook request) {
log.info("received callback for callId {}", request.getCallSid())
// rest of the controller.
}
}
You can parse all the parameters by adding to the TwilioWebhook class. You can see all the parameters that Twilio will send in the Twilio voice request documentation. There isn't a class in the Twilio SDK that does this for you though.
I am working with retrofit and need to be able to use multiple interceptors. Currently I am using one to automatically append an auth token but i need to be able to make calls with no auth token. If i add another interceptor with no auth token in the header how do I use that one instead of the auth token interceptor.
val interceptor: Interceptor = Interceptor { chain ->
val newRequest = chain.request().newBuilder().
addHeader("Auth_Token", pref.getString(PSPreferences.prefAuthKey, "")).
cacheControl(CacheControl.FORCE_NETWORK).
build()
chain.proceed(newRequest)
}
okHttpClient = OkHttpClient.Builder().
readTimeout(1, TimeUnit.MINUTES).
connectTimeout(1, TimeUnit.MINUTES).
addInterceptor(interceptor).build()
val retrofitInstance = Retrofit.Builder()
.baseUrl(APIEndpointInterface.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
apiInterface = retrofitInstance.create<APIEndpointInterface>(APIEndpointInterface::class.java)
OkHttpClient maintains a list of the interceptors which you can access, however it is an unmodifiable collection.
This leaves us with three options I believe:
Create two OkHttpClient instances, and by deduction two Retrofit
instances, one for the unauthenticated requests, and one for the
authenticated requests.
Check if you should use the interceptor, e.g. in your authentication interceptor, you can first check if there exists a key in your preferences for the token, and if so use it; if not, you simply proceed without modifying anything. You do this for your unauthenticated interceptor too. I think this is the easiest solution for your case.
Create a single interceptor, which will maintain a modifiable list
of interceptors which you can add and remove at will. You would need
to keep a reference to this interceptor, maybe make it a Singleton.
For the third option, I have provided a very simple example:
public class HttpRequestResponseInterceptor implements Interceptor {
public final List<RequestInterceptor> requestInterceptors = new ArrayList<>();
public final List<ResponseInterceptor> responseInterceptors = new ArrayList<>();
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
for (RequestInterceptor interceptor : requestInterceptors) {
request = interceptor.intercept(request);
}
Response response = chain.proceed(request);
for (ResponseInterceptor interceptor : responseInterceptors) {
response = interceptor.intercept(response);
}
return response;
}
public interface RequestInterceptor {
Request intercept(Request request) throws IOException;
}
public interface ResponseInterceptor {
Response intercept(Response response) throws IOException;
}
}
In this case you would need to implement the custom interfaces RequestInterceptor and ResponseInterceptor.
An example of what an implementation of these interfaces would look like:
public class ExampleInterceptor implements HttpRequestResponseInterceptor.RequestInterceptor,
HttpRequestResponseInterceptor.ResponseInterceptor {
#Override
public Request intercept(Request request) throws IOException {
return request.newBuilder().addHeader("REQUEST_HEADER", "EXAMPLE").build();
}
#Override
public Response intercept(Response response) throws IOException {
return response.newBuilder().addHeader("RESPONSE_HEADER", "EXAMPLE").build();
}
}
You would then need to add this interceptor to our main interceptor twice, once to requestInterceptors and once to responseInterceptors (or only to one of these if it intercepts only requests or only responses).
This example is far from complete. The benefit of this solution is that it adds the ability to add and remove interceptors without having to recreate the OkHttpClient instance. It requires extra work if you want to support retrying requests, for example.
The process of using a request body is described in the official API Declaration page as such:
#POST("users/new")
Call<User> createUser(#Body User user);
While there is no guide for creating the User object, I imagine it can look something like this:
public class User {
public String name;
public String group;
}
By extension, this would result in a request body like this:
{
"name": string,
"group": string
}
By default, these fields seem to be optional. What is the best way I can make them required?
There are many ways of accomplishing such a behavior. You can:
... validate your objects to be POSTed before you invoke a Retrofitted-service (user input forms, etc), and let it fail fast.
... validate your domain objects, centralized, in a Retrofit request converter and use chained converters
... validate your data transfer objects objects (if you have any), centralized, after they are converted from domain objects and prepared to be sent
... rely on the server API implementation and don't care for validation at the client side: no need to duplicate server logic ad-hoc, you may run out sync with the server API validation, you write more code, etc. This is what I was suggesting you in that comment.
If you really need to validate the request bodies before they are sent, you should go with the first option. If you want to make the validation fully centralized, you can implement a custom Retrofit converter to make pre-validation on fly. (The code below uses Java 8 and a little bit of Google Guava, Retrofit 2 and Gson, however it can be easily reworked for another components).
Consider these:
interface IService {
#POST("/")
Call<String> post(
#Body User user
);
}
final class User {
final String name;
final String group;
User(final String name, final String group) {
this.name = name;
this.group = group;
}
}
Now we can implement Retrofit-stuff. The following mockOkHttpClient is a mock OkHttpClient to consume any request and respond with HTTP 200 OK and "OK".
private static final OkHttpClient mockOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> new Response.Builder()
.request(chain.request())
.protocol(HTTP_1_0)
.code(HTTP_OK)
.body(ResponseBody.create(MediaType.parse("application/json"), "\"OK\""))
.build()
)
.build();
Now let's make a simple test:
final Iterable<Retrofit> retrofits = ImmutableList.of(
getAsIsRetrofit(),
getValidatedDomainObjectsRetrofit(),
getValidatedDataTransferObjectsRetrofit()
);
final User user = new User("user", "group");
for ( final Retrofit retrofit : retrofits ) {
final IService service = retrofit.create(IService.class);
final String message = service.post(user).execute().body();
System.out.println(message);
}
As you can see, there are three Retrofit instances that are instantiated with different configurations to demonstrate each of them.
The following Retrofit instance does not care the validation itself. And this is another time I recommend you to go with: simply post what you get as is and let the server API implementation deal with it itself. Consider the API implementation to return nice responses like HTTP 400 Bad Request, etc.
private static Retrofit getAsIsRetrofit() {
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
The following Retrofit instance validates the given User object before it's converted to a Gson-friendly representation (depends on if you have domain objects to data transfer object transformations in your application):
private static Retrofit getValidatedDomainObjectsRetrofit() {
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(new Converter.Factory() {
#Override
public Converter<?, RequestBody> requestBodyConverter(final Type type, final Annotation[] parameterAnnotations,
final Annotation[] methodAnnotations, final Retrofit retrofit) {
if ( type != User.class ) {
return null;
}
final Converter<Object, RequestBody> nextConverter = retrofit.nextRequestBodyConverter(this, type, parameterAnnotations, methodAnnotations);
return (Converter<Object, RequestBody>) value -> {
if ( value instanceof User ) {
final User user = (User) value;
requireNonNull(user.name, "name must not be null");
requireNonNull(user.group, "group must not be null");
}
return nextConverter.convert(value);
};
}
})
.addConverterFactory(GsonConverterFactory.create())
.build();
}
And the next one validates data transfer objects before they are written to output streams. Probably the most low-level instance here.
private static Retrofit getValidatedDataTransferObjectsRetrofit() {
final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new TypeAdapterFactory() {
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
if ( typeToken.getRawType() != User.class ) {
return null;
}
final TypeAdapter<T> delegateTypeAdapter = gson.getDelegateAdapter(this, typeToken);
return new TypeAdapter<T>() {
#Override
public void write(final JsonWriter out, final T value)
throws IOException {
if ( value instanceof User ) {
final User user = (User) value;
requireNonNull(user.name, "name must not be null");
requireNonNull(user.group, "group must not be null");
}
delegateTypeAdapter.write(out, value);
}
#Override
public T read(final JsonReader in)
throws IOException {
return delegateTypeAdapter.read(in);
}
};
}
})
.create();
return new Retrofit.Builder()
.client(mockOkHttpClient)
.baseUrl("http://whatever")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
Note that requireNonNull is a JDK 8 method, and if you want something like #NotNull, you can implement your own annotation processor, or find such an implementation in the Internet considering my implementation idea useless. :) However, I think you'd like the as-is approach the most.
Retrofit Documentation says:
"By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody...Converters can be added to support other types"
This implies I should be able to make a api call WIHTOUT using the GSON converter, and get my response in the form of a "ResponseBody" object.
but I still get error
java.lang.IllegalArgumentException: Unable to create converter for class com.squareup.okhttp.ResponseBody
here is my code
#GET("v1/search")
Call<ResponseBody> getArtists(#Query("q") String name, #Query("type") String searchType);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.spotify.com/")
.build();
api = retrofit.create(SpotifyApi.class);
api.getArtists(searchBox.getText().toString(), "artist")
.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Basically for I want to be able to use Retrofit in its purest/simplest form and just get a basic/raw response back. this is not for a real app, it's for experimentation.
You need to use okhttp3.ResponseBody from OkHttp 3.x (which Retrofit depends on). That error message indicates you are using the type from OkHttp 2.x.