简体   繁体   中英

How to get String in response using Retrofit 2?

I would like to understand how Retrofit works, but the official documentation is very weak.

I need to make a very simple GET request and get the response as a String .

Now I use standard HTTPUrlConnection and it works nicely, just request - response

Can anyone tell me how to get a String response without converting it to an object or something like that?

You can use ScalarsConverterFactory for strings and both primitives and their boxed types to text/plain bodies. Add this dependency to your build.gradle file:

compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

Try this:

public interface ExampleService {
@GET("/users/{user}/repos")
Call<String> listRepos(@Path("user") String user);
}

And add ScalarsConverterFactory to your builder:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();

You can then retrieve this string like this:

Call<String> call = exampleService.listRepos(user);
Response<String> response = call.execute();  
String value = response.body();  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM