How to Get String Response from Retrofit2

Get String response body from retrofit2

Create this class

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
@Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}

use it with

Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(new ToStringConverterFactory())
.build();

EDIT:
You have to define it as

@GET("/loginUser")
public Call<String> login(
@Query("email") String email,
@Query("password") String password);

There is no callback supported in retrofit2 so you have to remove that. To make it asynchronous, you have to do

Call<String> call = service.login(username, password);
call.enqueue(new Callback<String>() {}

EDIT The above code was for retrofit2 beta 3. For retrofit:2.1.0, you have to create ToStringConverterFactory as -

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
@Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations, Retrofit retrofit) {

if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}

GOOD TO KNOW: Incase you want to have multiple converters (e.g. a String converter as shown above and also a GSON converter):

Make sure you specify the special-purpose converters first (e.g. String converter) and general converters (like Gson) last!

Converters will be called by the order they have been added, if a converter consumed the response, the follwoing converters will not be called.

Retrofit get String response

You can get the response from api and convert it to string like this:

 public interface RetrofitService{
@GET("/users")
Call<ResponseBody> listRepos();//function to call api
}

RetrofitService service = retrofit.create(RetrofitService.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());//convert reponse to string
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});

Retrofit 2: Get JSON from Response body

Use this link to convert your JSON into POJO with select options as selected in image below

Sample Image

You will get a POJO class for your response like this

public class Result {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("Username")
@Expose
private String username;
@SerializedName("Level")
@Expose
private String level;

/**
*
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

/**
*
* @return
* The username
*/
public String getUsername() {
return username;
}

/**
*
* @param username
* The Username
*/
public void setUsername(String username) {
this.username = username;
}

/**
*
* @return
* The level
*/
public String getLevel() {
return level;
}

/**
*
* @param level
* The Level
*/
public void setLevel(String level) {
this.level = level;
}

}

and use interface like this:

@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);

and call like this:

Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}else Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time

}

@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE

}
});

and use dependencies in Gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'

NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create()) in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create()) from Retrofit. If not then use the above solution

How to get String inside object Gson/Retrofit2

You can request the JSON directly in your browser here. Looking closely at this data, you will see that items[0] doesn't have a property title. Instead, there is a property volumeInfo that contains title. Your Retrofit entity class needs to correctly navigate to that property in order to get the data you need.

how to get json response using retrofit

Try this :

Api client :

public class ApiClient {

public static final String BASE_URL = "http://zeenatkhanniazai.com/services/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Api interface :

public interface ApiInterface {

@POST("login.php")
@FormUrlEncoded
Call<users> getTopRatedMovies(@Field("uemail") String uemail, @Field("upassword") String upassword);

}

User class :

public class users
{
@SerializedName("message")
private String message;
@SerializedName("status")
private String status;

public String getStatus() {
return status;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public void setStatus(String status) {
this.status = status;
}
}

In main activity :

call.enqueue(new Callback<users>() {
@Override
public void onResponse(Call<users> call, Response<users> response) {
progressDoalog.dismiss();
int statusCode = response.code();
String movies = response.body().getMessage();

Log.e("sdasd",movies);
//Log.w("response",new Gson().toJson(response));
Log.w("response",new GsonBuilder().setPrettyPrinting().create().toJson(response));
// recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.list_item_movie, getApplicationContext()));
}

@Override
public void onFailure(Call<users> call, Throwable t) {
progressDoalog.dismiss();
// Log error here since request failed
Log.e(TAG, t.toString());
}
});

Output :

Login unsuccessful :( This account doesn't exist or the email is not verified yet! try asking admin for activation and then logging in ;)

Response :

"body": {
"message": "Login unsuccessful :( This account doesn\u0027t exist or the email is not verified yet! try asking admin for activation and then logging in ;)",
"status": "0"
},


Related Topics



Leave a reply



Submit