Rectrofit 2.3.0 Response As a String

Scalars Converter for Plain Strings


To receive plain-text or plain-string responses you can utilize the scalars converter. You can integrate the converter by adding it as a dependency to your app's build.gradle:
dependencies {  
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'

// Retrofit Scalars Converter
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
}

Next, you need to describe the endpoint you want to interact with. In this demo case, you'll use a GET request with the dynamic URL feature to pass any URL to the method, and set the response type as String.
@GET()
Call<String> getStringResponse(@Url String url);

You've finished the preparations. Next, you can use Retrofit to execute requests with the scalars converter and the created endpoint. You'll create a Retrofit object with the Retrofit builder and configure it to use the scalars converter:
Retrofit retrofit = new Retrofit.Builder()  
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl("https://your.base.url/")
.build();

The final step is to use the Retrofit object to execute a request:
ScalarService scalarService = retrofit.create(ScalarService.class);  
Call<String> stringCall = scalarService.getStringResponse("https://futurestud.io");
stringCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
String responseString = response.body();
// todo: do something with the response string
}

}

@Override
public void onFailure(Call<String> call, Throwable t) {

}
});

In the code snippet above, you're executing a GET request for our homepage futurestud.io. Consequently, you'll receive a long string back (which is actually the website's HTML source). You can also use the above approach to receive plain strings from your API.

Unknown

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

0 comments:

Hot-product

Best Watch Store

Popular Posts

Contact Form

Name

Email *

Message *