I need to execute request via Retrofit :
url = http://ENDPOINT_URL/users/77?expand=followers,image,followees
Code :
#GET(ENDPOINT_URL+"users/{user_id}?expand=" WHAT NEED PRESENT HERE???)
void getUserInfo(#Path("user_id) int userId, String... expand)
For userId i use Path annotation, but how i can say to Retrofit, that I need to use array items separated via comma?
Related
This question already has answers here:
Retrofit2 Post body as Json
(2 answers)
Closed 4 years ago.
How can I post to the server? I need to post an JSON object using Retrofit 2. My JSON object is
{
"test_id":5,
"user_id":null,
"org_id":2,
"schedule_id":15,
"group_id":null,
"next_section_id":"",
"current_section":
{}
}
make give json into one pojo class and pass into api calling like..
#POST("path")
Call<ResponseData> passJsonData(#Body JsonData jsonData); // here pass your request data pojo class object..
when calling that time only create object and pass all data into object and pass into api call method.
like ..
JsonData data=new JsonData();
data.setId("1");
data.setName("Abcd");
Call<ResponseData> responseCall =apiInterface.passJsonData(data);
Below are some ways to achieve this:
1.
#POST("/path")
void sendPost(#Body EventPayload body, Callback<Response> onSuccess);
here EventPayload is the POJO representation of your request
2.
#POST("/path")
void sendPost(#Body String body, Callback<Response> onSuccess);
here body is the serialized JSON in the string form
I'm using Retrofit 2 to call API in Android App. I have a API, using POST, which have a String param in Query Tag. I do everything like doc suppose and I test this API successfully in Test Page. I can run another API correctly so the problem is not the way I use Retrofit 2.
Here is my interface:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query("list") String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
Here is my implementation:
ArrayList<String> id = new ArrayList<>();
id.add("4782947293");
JSONArray jsonArray = new JSONArray(id);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("list", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String list = jsonObject.toString();
Log.e(TAG, "list: " + list);
apiInterface.getListFriend(21, list, 1,1,"AHHIGHTJGI").enqueue(new Callback<GetListFriendDataResponse>() {
#Override
public void onResponse(Call<GetListFriendDataResponse> call, Response<GetListFriendDataResponse> response) {
Log.e(TAG, " response code: "+ response.code());
}
#Override
public void onFailure(Call<GetListFriendDataResponse> call, Throwable t) {
}
});
I always get response code: 400 when use this API.
I'm focusing the "list" var. "list" is a JSON text but I wonder if method "jSon.toString()" is right to get a String from a JSONObject, which can using in Retrofit 2. List param form is:{"list":["12332"]} .
Please help me!
Questions
1) Why you are creating JSONObject and JSONArray on your own?
2) You are creating string using whatever you are creating json.
Eg: {list:["123","456"]}
you are trying pass whole json, I think, instead you need to pass just the array of string to the list key.
Request Sending
{
list:["123","456"]
}
suppose the above json is the request you want to send to server
Now, create model class goto http://jsonschema2pojo.org and paste your json and select json and gson at right side and click on preview.
It will show the classes to map you json to model. Use this model class to set the list to the key in your json
I found my problem. The JSON text contains some special character so I need to convert them to URL encode.
Correct request URL like this:
http://54.169.215.161:8080/users/29/add_friend?list=%7B%22list%22%3A%5B%2215536%22%5D%7D&platform=google
By using Retrofit 2, it uses the URL:
http://54.169.215.161:8080/users/29/add_friend?list={%22list%22:[%2215536%22]}&platform=google
So I get Bad Request Response code.
Retrofit 2 also provides method to convert char sequence to URL encode but it 's not enough. So I don't use Retrofit 's convert method by using this code: encode= true.
so my interface is:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query(value = "list",encoded = true) String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
And I manually convert JSON text to URL encode by code:
list = list.replace("{", "%7B");
list=list.replace("]", "%5D");
list=list.replace("[", "%5B");
list=list.replace(":", "%3A");
list=list.replace("}","%7D");
list = list.replace("\"", "%22");
That's all. Now I can get data by using API.
Suggestion: If u have the same problem, check the URL retrofit return in response and compare to correct URL to see special character, which is not converted to URL encode.
I am using Retrofit to make an api call. The top level object is named depending on the query parameters of the request. For example, a request like this:
api.somewebsite.com/1.0/mix_info?mix_id=69
returns a response like this:
{"69":{
"mix_id":"69",
"mix_title":"A Title",
"mix_file":"https:example.com/mp3",
"mix_genres":"House,Pop",
"mix_dj_id":"57",
"number_votes":"390",
"station":"1"
}
}
Heres a screenie as well that kinda shows the format:
http://prnt.sc/axltcd
Basically, depending on the number passed into the url mix_id= query becomes the name of the top level json object returned in the response.
I was able to hack together something that kinda works:
I have a model Response class which has a member variable that is the top level object, and I use Retrofit's #SerializedName("69") to explicity set the name. This, of course, will only work for a request with the id of 69, otherwise the response returns null object.
It looks like this:
public class Response {
#SerializedName("69")
private _69 _69;
}
Anyway, I'm looking for a way to properly handle these oddly formatted responses. How would this be done?
You can receive your response as JsonElemen, convert it to JsonObject and get element by global variable which you was using for send request.
Response:
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
JsonElement jsonElement = response.body();
JsonObject jObj= jsonElement.getAsJsonObject();
JsonObject number= jObj.get(CONSTANT_WHICH_YOU_USED_FOR_REQEST).getAsJsonObject();
}
Feel free to ask me if any.
I have an Android application acting as a client to my back end server.
I am doing a POST http request with a help of Retrofit lib with a String in the body.
Problem is, Retrofit is most likely escaping double quotes when using GSON builder.
That results in a field in my DB containing double quotes, example: "example_gcm_token".
I need to know whether I should handle that on server side or on client side and how to do that.
I assume it shouldn't be on the server side as it would mean I have to remove escaped quotes for every single endpoint.
#POST ("/Maguss/users/{userId}/gcmtoken")
Call<Void> setGcmToken(#Path("userId") Long userId, #Body StringEntity gcmToken);
I would try to replace the StringEntity with a POJO:
public class SetGcmTokenRequest {
#SerializedName("gcmtoken")
private String gcmToken;
public String getGcmToken() {
return gcmToken;
}
public void setGcmToken(String gcmToken) {
this.gcmToken = gcmToken;
}
}
And change the interface like this:
#POST ("/Maguss/users/{userId}/gcmtoken")
Call<Void> setGcmToken(#Path("userId") Long userId, #Body SetGcmTokenRequest setGcmTokenRequest);
I am using retrofit for api calling in my android app. In one of my request url of request is like this:
/v1/employee/1?employeeId=50124
my retrofit method is:
#GET("/v1/xyz/{employeeId}?companyId={companyId}")
void getEmployee(#Path("employeeId")int employeeId, #Path("companyId") int companyId, Callback<List<Model>> callback);
but when i call api it throws error, please help how to append url like this in retrofit GET request.
For dynamic query parameters use #Query.
Try using the below code:
#GET("/v1/xyz/{employeeId}")
void getEmployee(#Path("employeeId")int employeeId, #Query("companyId")
int companyId, Callback<List<Model>> callback);