I am getting a response from the GET method in the form of
{data : { "type " : User ........ "attribute" : { "isemailverified" : false.....}....}
I want to fetch the value of isemailverified
I am using Retrofit to fetch data
useCaseFactory.getUserDomainModel().GetUser(userId, withDataArray, null, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
System.out.println("ERROR: " + e.getMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody responseBody = response.body();
System.out.println(response.body().string());
}
Related
In my retrofit JSON response there is a single value without any key and type.In my JSON i have passed three-element as per need and now i get a response as shown below. so how can I fetch that response?
My JSON of Response looks like -
successful
This is my JSON code-
private void ASSIGN_DATA() {
ApiInterface apiInterface=ApiClient.getClient().create(ApiInterface.class);
Call<ArrayList<price_get_set>> call=apiInterface.assignItemToJson(select_date.getText().toString(),
id,item_list);
call.enqueue(new Callback<ArrayList<price_get_set>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<ArrayList<price_get_set>> call, Response<ArrayList<price_get_set>> response) {
progress.dismiss();
Log.d("URL::",response.toString());
Log.d("new URL::",response.body().toString());
try {
if (response.isSuccessful()) {
Toast.makeText(Items_List.this, "Successs", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Items_List.this, Item_Accept_Reject_List.class);
startActivity(intent);
}
else
Toast.makeText(Items_List.this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
catch (Exception ex){
Log.e("ERROR::",ex.getMessage());
}
}
#Override
public void onFailure(Call<ArrayList<price_get_set>> call, Throwable t) {
progress.dismiss();
Log.i("FAILURE ERROR::",t.getMessage());
}
});
}
You can use response.body().string().
It will convert your response in String.
Example On Your onResponse method of API you have to use this code.
#Override
public void onResponse(Response<ResponseBody> response) {
try {
String responseString = response.body().toString();//This a response as string
Log.d("Response : " + responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
I use okhttp to get text of certain url.
url I try to get is
https://firebasestorage.googleapis.com/v0/b/famhouse.appspot.com/o/branchname%2Ftextfile?alt=media&token=a58b07a4-ddee-4ece-8222-0854a6c2a713
as you can see, it only have body saying "Testtest"
I get response well and I logged response.body().toString() but it says
okhttp3.internal.http.RealResponseBody#e640919
What I expect to see on log is Testtest
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this.getApplicationContext();
checkPermission();
OkHttpHandler okHttpHandler= new OkHttpHandler();
okHttpHandler.execute("https://firebasestorage.googleapis.com/v0/b/famhouse.appspot.com/o/branchname%2Ftextfile?alt=media&token=a58b07a4-ddee-4ece-8222-0854a6c2a713");
}
public class OkHttpHandler extends AsyncTask {
OkHttpClient client = new OkHttpClient();
#Override
protected Object doInBackground(Object[] objects) {
Request request = new Request.Builder()
.url("https://firebasestorage.googleapis.com/v0/b/famhouse.appspot.com/o/branchname%2Ftextfile?alt=media&token=a58b07a4-ddee-4ece-8222-0854a6c2a713").addHeader("Accept", "application/json")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
Log.e("dialog","response is : "+response.body().toString());
Log.e("dialog","response is : "+response.code());
}
}
});
return null;
}
}
you should use response.body().string()
I've implemented okhttp in my android client for network calls.
When i get a failure response i get the failure code and the text related to the code as a message but i don't get the custom failure response that the server sends me.
In my failure response in the implemented code the message i get is just "Bad Request".
Whereas the same response from the browser is as follows.
How do i get the error message the server is giving me back?
My code
private void executeCall(Request request, final ResponseListener listener) {
mOKHttpClient.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
postFailure(listener, (String) call.request()
.tag(),e.toString());
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
String responseString = response.body().string();
postSuccess(listener, (String)call.request().tag(), responseString);
}
else {
postFailure(listener, (String)call.request().tag(),response.code()+","+response.message());
}
}
});
}
Here's my response in case of failure.
You will have to catch error response by body() because response.message() returns HTTP status message.
In the screen shot provided by you:
Status is broken down in OkHttp like response.code() for HTTP status code which is 400 in your case and response.message() for HTTP status message which is Bad Request in your case.
The body of the response (be it success or failure) is response.body(). And if you want to get it as a String, then call response.body().string().
#Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
String responseString = response.body().string();
postSuccess(listener, (String)call.request().tag(), responseString);
}
else {
String errorBodyString = response.body().string();
postFailure(listener, (String)call.request().tag(),response.code()+","+errorBodyString);
}
}
As per comments:
Since you want to read Message object from the response, try to do like this:
JSONObject object = new JSONObject (response.body().string());
String messageString = object.getString("Message");
if you are trying to get (okhttp3.ResponseBody) errorResponse from Retrofit response do this..
// Retrofit onResponseCall
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.errorBody() != null) {
try {
Log.e("errorResponse","" + response.errorBody().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Currently, I am using Retrofit to get data from api. But the format of data is a bit different from other format such as :
["tayl",["taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"]]
So, I want to ask for the best solution to parse values to get a list as below if I want to use retrofit:
"taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"
The content of the file above is the data which GoogleAutoComplete Api returned for me with the link below :
http://suggestqueries.google.com/complete/search?client=firefox&q=tayl
I implemented the code as below but it is not good:
#Headers({
"Accept: application/json",
"Content-Type: application/json; charset=UTF-8"
})
#GET("complete/search?")
Call<ResponseBody> getAutoComplete(#Query(#Query("q")String query);
The below is response code which I am using:
autoCompleteCall = googleApi.getAutoComplete(client, keyword);
autoCompleteCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response != null &&
response.body() != null) {
System.out.println(" String response======= " + response.body().toString());
return;
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
But the responsebody returned for me is null.
Please help me in this case.
Thanks.
Define the API endpoint in an interface as follows:
#GET("complete/search")
Call<ResponseBody> getAutoComplete(
#Query("client") String client,
#Query("q") String query);
Make the network request as follows:
Call<ResponseBody> call = service.getAutoComplete("firefox", "tayl");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
try {
// autocompleteOptions => ["tayl",["taylor swift","taylor lautner",...
String autocompleteOptions = body.string();
JSONArray jsonArray = new JSONArray(autocompleteOptions).getJSONArray(1);
// list => "taylor swift","taylor lautner",...
ArrayList<String> list = GetAutocompleteOptions(jsonArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
private ArrayList<String> GetAutocompleteOptions(JSONArray jsonArray) throws JSONException {
ArrayList<String> list = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}
}
return list;
}
I am using Retrofit to send a POST request to a server. The body of the POST must be in the form jdata={"key1":"value1",...} along with a Content-Type header set to application/x-www-form-urlencoded. I found a similar question but the accepted answer is not working.
Here's what I tried -
My interface
public interface APIHandler {
#Headers("Content-Type: application/x-www-form-urlencoded")
#FormUrlEncoded
#POST(URL)
Call<ResponseBody> getdata(#Field("jdata") String jdata);
}
Call function
public void load() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("BASE_URL")
.addConverterFactory(GsonConverterFactory.create())
.build();
// prepare call in Retrofit 2.0
APIHandler iAPI = retrofit.create(APIHandler.class);
String requestBody = "{\"id\":\"value\",\"id1\":\"value2\"}"
Call<ResponseBody> call = iAPI.getData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> c, Response<ResponseBody> response) {
if (response.isSuccess()) {
ResponseBody result = response.body();
String gs = new Gson().toJson(result);
Log.d("MainActivity", "response = " + gs + " status: " + statusCode);
} else {
Log.w("myApp", "Failed");
}
}
#Override
public void onFailure(Call<ResponseBody> c, Throwable t) {
}
});
}
But I receive response = null and status = 200. What am I doing wrong? The expected response is only a string and not a JSON array.
I am leaving this here so that it helps someone.
The above code is correct. As I mentioned in the last line, a plain string response was expected. But since it is not a JSON response, the conversion probably did not work and the response was null. The only solution I could find was to directly convert the response to string -
try {
stresp = response.body().string()
Log.d("MainActivity", "response = " + stresp + " status: " + statusCode);
} catch (IOException e) {
//Handle exception
}
There might be a better way to handle this but that worked for me!
You can use like that. I have tested this and it working fine
public interface APIHandler {
#POST(URL)
Call<ResponseBody> getdata(#Body JsonObject body);
}
Request body:
JsonObject requestBody = new JsonObject();
requestBody.addProperty("id", "value1");
requestBody.addProperty("id1", "value2");
Prepare call in Retrofit 2.0
APIHandler iAPI = retrofit.create(APIHandler.class);
And Call function :
Call<ResponseBody> call = iAPI.getData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> c, Response<ResponseBody> response) {
if (response.isSuccess()) {
String result = response.body().string();
Log.d("MainActivity", "response = " + result);
} else {
Log.w("myApp", "Failed");
}
}
#Override
public void onFailure(Call<ResponseBody> c, Throwable t) {
}
});