Using retrofit to read string content from api - android

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;
}

Related

Unable to send JSONObject using Retrofit POST?

So I have a JSONObject's object and I need to send the object to backend using Retrofit. It is a POST api and the body is of jsonObject. The following code I have written send JSONObject.
This is interface
public interface ApiSet {
#POST(Api.DELETE_EWAYBILL)
Call<JsonElement> deleteEwaybill(#Body JSONObject jsonObject);
}
This code I written in adapter
Call<JsonElement> call = ApiController.getInstance()
.getApi()
.deleteEwaybill(deleteEwayObj);
Log.e("vin1", deleteEwayObj.toString());
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, retrofit2.Response<JsonElement> response) {
if (response.isSuccessful()) {
Gson gson = new Gson();
JsonElement jsonElement = response.body();
if(jsonElement.isJsonObject()){
JsonObject jsonObject = jsonElement.getAsJsonObject();
PostResponse postResponse = gson.fromJson(jsonObject, PostResponse.class);
if(postResponse.isSuccess()){
((Activity) context).recreate();
}else{
Toast.makeText(context,postResponse.getMessage(),Toast.LENGTH_LONG).show();
Log.e("vin1", "delete invoice error = "+postResponse.getMessage());
}
}
}
customProgressDialog.dismiss();
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.e("vin1", "retrofit failure = " + t.getMessage());
customProgressDialog.dismiss();
t.printStackTrace();
}
});

How to get JSON object using Retrofit?

I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.
The JSON in ALE2 file
{
"a1":[...],
"a2":[...],
"a3":[...]
}
Code
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
#Override
public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {
}
#Override
public void onFailure(Call < JSONObject > call, Throwable t) {
}
});
RetrofitInterface
public interface RetrofitInterface {
#GET("ALE2")
Call<JSONObject> getData();
}
I don't want to store them in any model I just want to get the JSON as a string
Your interface should look like this :
public interface RetrofitInterface {
#GET("ALE2")
Call<ResponseBody> getData();
}
To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is how you can set string in JSON object.

Implementing custom header for retrofit and i get No Retrofit annotation found, error

this below code is calling webservice which i want to implementing that with Retrofit on Android, but i get this error:
No Retrofit annotation found
calling Web Service with CURL:
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
-H "X-User-Id: aobEdbYhXfu5hkeqG" \
http://localhost:3000/api/v1/channels.list
i wrote this interface like with above code:
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
ChannelsList channelsList);
}
and i'm calling this rest Web Service by this code:
ChannelsList channelsList = new ChannelsList();
Call<List<ChannelsList>> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD",
channelsList);
call.enqueue(new Callback<List<ChannelsList>>() {
#Override
public void onResponse(Call<List<ChannelsList>> call, final Response<List<ChannelsList>> response) {
Log.e("contentLength ", response.code() + "");
}
#Override
public void onFailure(Call<List<ChannelsList>> call, Throwable t) {
t.printStackTrace();
}
});
whats problem of my code that i can't call and i get error?
You forgot #Body annotation. And since you have to send a body, you must create a POST to your API. If is not a POST, you must find how to send ChannelsList in order to be a GET request because is depending your server implementation.
#POST("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
#Body ChannelsList channelsList);
problem solved by this below code:
interface:
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<ResponseBody> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId);
}
call request and get response:
ChannelsList channelsList = new ChannelsList();
Call<ResponseBody> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String jsonString = response.body().string();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonarray = jsonObject.getJSONArray("channels");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Err: ", t.getMessage());
}
});

Access sent parameter in onResponse of retrofit 2

I create a request with retrofit2 and send parameter to server, how can access sent parameter in onResponse?
retrofit = new Retrofit.Builder()
.baseUrl("baseAddress")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiBase serviceSetParam = retrofit.create(ApiBase.class);
Call<String> myCall = serviceSetParam.setParam("data1","data2");
Callback<String> myCallback = new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
//i need access data1 & data2 Here !
if (response.isSuccessful()) {
String mResponse= response.body();
} else {
Utils.Log("unSuccessful");
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Utils.Log("onFailure");
}
};
myCall.enqueue(myCallback);
here the send param method:
#FormUrlEncoded
#POST("set")
Call<String> setParam(#Field("param1") String param1, #Field("param2") String param2);
in onResponse method of your request, test this code:
try {
BufferedSink bf = new Buffer();
call.request().body().writeTo(bf);
Log.i("params are",bf.buffer().readUtf8().toString());
} catch (IOException e) {
e.printStackTrace();
}
You need to get the original Request from OkHttp.
List<String> pathSegments = original(response.raw()).url().pathSegments();
given:
static Request original(Response response) {
while (true) {
Response prior = response.priorResponse();
if (prior == null) {
break;
}
response = prior;
}
return response.request();
}

Retrofit POST raw string body

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) {
}
});

Categories

Resources