I have this function
#GET("/users?filters[0][field]={param}&filters[0][operator]=equals&filters[0][value]={value}")
UserDto retrieveUsersByFilters(#Path("param") String nameFilter, #Path("value") String value);
I try to call it like this :
UserDto currentUser = interfaceUser.retrieveUsersByFilters(User.LOGIN, login);
But i have error :
retrofit.RetrofitError: InterfaceUser.retrieveUsersByFilters: URL query string "filters[0][field]={param}&filters[0][operator]=equals&filters[0][value]={value}" must not have replace block.
I already test url on firefox and it work fine.
Thank's for your responses
Edit
Solution:
#GET("/users?filters[0][operator]=equals")
UserDto retrieveUsersByFilters(
#Query("filters[0][field]") String nameFilter,
#Query("filters[0][value]") String value);
Query params have their own annotation which automatically appends to the URL.
#GET("/users?filters[0][operator]=equals")
UserDto retrieveUsersByFilters(
#Query("filters[0][field]") String nameFilter,
#Query("filters[0][value]") String value);
You can read more about #Query on its Javadoc
URL="/api-mobile_prateek2.php?method=getProductById&pid="
#GET("/api-mobile_prateek2.php?method=getProductById")
Call<Product> responseproduct(#Query("pid") String pid);
dont put the pid in the #GET,, Retrofit automatically fix the url, using #Query
From the JavaDoc:
Example 1:
#GET("/friends")
Call<ResponseBody> friends(#Query("page") int page);
Calling with foo.friends(1) yields /friends?page=1.
Example with null:
Example 2:
#GET("/friends")
Call<ResponseBody> friends(#Query("group") String group);
Calling with foo.friends(null) yields /friends.
Array/Varargs Example:
Example 3:
#GET("/friends")
Call<ResponseBody> friends(#Query("group") String... groups);
Calling with foo.friends("coworker", "bowling") yields /friends?group=coworker&group=bowling.
Parameter names and values are URL encoded by default. Specify encoded=true to change this behavior.
Example 4:
#GET("/friends")
Call<ResponseBody> friends(#Query(value="group", encoded=true) String group);
Calling with foo.friends("foo+bar")) yields /friends?group=foo+bar.
Don't put your values directly in the path, but prefer in the method signature.
Not completely sure, but try something like this :
#GET("/users?filters[0][operator]=equals")
UserDto retrieveUsersByFilters(#Path("filters[0][field]") String nameFilter, #Path("filters[0][value]") String value);
Related
I want url like this
baseurl/dealer/index.php?r=rest/packInfo
I am doing like this
#FormUrlEncoded
#POST("/dealer/index.php?r=rest/{method}")
void getDealersPacks(#Path("method") String method,
#Field("cd_dealer_id") String cd_dealer_id,
#Field("country_code") String country_code,
#Field("business_type")String business_type);
And i am getting error
URL query string "r=rest/{method}" must not have replace block. For dynamic query parameters use #Query.
You are passing #Path annotation for query parameter.
You can do it this way :
#FormUrlEncoded
#POST("/dealer/index.php")
void getDealersPacks( #Query("r") String query, #Field("cd_dealer_id") String cd_dealer_id, #Field("country_code") String country_code, #Field("business_type") String business_type);
Now , pass "rest/packInfo" or any other dynamic value in query parameter, it will work.
Hope , it helps !!
I want to get JSON data using retrofit get this error
Caused by: java.lang.IllegalArgumentException: URL query string
"q={text}&langpair={l_from}|{l_to}" must not have replace block. For
dynamic query parameters use #Query.
My code is
// example of my site
// http://mytempsite.com/get?q=hello friend&langpair=en|ur
#GET("get?q={text}&langpair={from}|{to}")
Call<ApiService> getJsonData(#Query("text") String text,
#Query("from") String from,
#Query("to") String to);
And my calling request
Call<ApiService> call = apiService.getJsonData("hello word","en","ur");
But when i use statically like this it will work.
#GET("get?q=Hello Word&langpair=en|ur")
Call<ApiService> getJsonData(#Query("text") String text,
#Query("from") String from,
#Query("to") String to);
try this code:
#GET(".")
Call<ApiService> getJsonData(#Query("q") String text,
#Query("langpair") String langpair);
Call<ApiService> call = apiService.getJsonData("hello word","en|ur");
So I'm looking to make a request to our api to log in a user, however there is a section that gets encoded in the Retrofit 2 method even though its set as encoded = true. The base url is https://testapi.test.ie The parameter I pass as the serverext is mdc.php?action= However even after setting encoded = true the resulting request body is: https://testapi.test.ie/mdc.php%3Faction=login_user&ts=1482924232742 where I require it to be: https://testapi.test.ie/mdc.php?action=login_user&ts=1482924232742 So I can see the issue is the ? symbol. Below is my retrofit method, if anyone can help with this I would appreciate it in order to achieve the correct
#retrofit2.http.POST("/{serverext}login_user&ts={timestamp}")
#retrofit2.http.Multipart
Call<LoginResponseModel> loginUser(#retrofit2.http.Path(value = "serverext", encoded = true) String server,
#retrofit2.http.Part(Constants.USER) String username,
#retrofit2.http.Part(Constants.PASS) String password,
#retrofit2.http.Path("timestamp") Long timestamp);
You use it incorrect. Path is path, Query is query. You need to rewrite your code to use this separately.
#retrofit2.http.POST("{serverext}")
#FormUrlEncoded
Call<LoginResponseModel> loginUser(#retrofit2.http.Path(value = "serverext", encoded = true) String server,
#retrofit2.http.Field(Constants.USER) String username,
#retrofit2.http.Field(Constants.PASS) String password,
#retrofit2.http.Query("timestamp") Long timestamp,
#retrofit2.http.Query("action") String action);
loginUser("mdc.php", username, pass, 42, "login_user")
You need to use #FormUrlEncoded . And you don't need to include package name in all declarations! just import them! its more neat and clean!
#POST("/{serverext}login_user&ts={timestamp}")
#Multipart
#FormUrlEncoded
Call<LoginResponseModel> loginUser(#Path(value = "server", encoded = true) String server,
#Part(SyncStateContract.Constants.USER) String username,
#Part(SyncStateContract.Constants.PASS) String password,
#Path("timestamp") Long timestamp);
I'm trying to send a array / list of String to my REST server through Spring RestTemplate.
This is on my android side:
private List<String> articleids = new ArrayList<>();
articleids.add("563e5aeb0eab252dd4368ab7");
articleids.add("563f2dbd9bb0152bb0ea058e");
final String url = "https://10.0.3.2:5000/getsubscribedarticles";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("articleids", articleids);
java.net.URI builtUrl = builder.build().encode().toUri();
Log.e("builtUrl", builtUrl.toString());
The builtUrl is: https://10.0.3.2:5000/getsubscribedarticles?articleids=%5B563e5aeb0eab252dd4368ab7,%20563f2dbd9bb0152bb0ea058e%5D
On the server side:
#RequestMapping(value = "/getsubscribedarticles", method = RequestMethod.GET)
public List<Posts> getSubscribedPostFeed(#RequestParam("articleids") List<String> articleids){
for (String articleid : articleids {
logger.info(" articleid : " + articleid);
}
}
The server logs:
.13:11:35.370 [http-nio-8443-exec-5] INFO c.f.s.i.ServiceGatewayImpl
- articleid : [563e5aeb0eab252dd4368ab7
.13:11:35.370 [http-nio-8443-exec-5] INFO c.f.s.i.ServiceGatewayImpl
- articleid : 563f2dbd9bb0152bb0ea058e]
Which I can see is wrong as the list should not have a '[' on the first item and a ']' on the last item.
I have read this thread How to pass List or String array to getForObject with Spring RestTemplate but it does not actually answer the question.
The selected answer issues out a POST request, but I want to do a GET request , also it requires an additional object to work to hold the list and I would prefer to not create extra objects if I can do it with Spring RestTemplate natively.
Using Java 8, this worked for me :
UriComponentsBuilder builder = fromHttpUrl(url);
builder.queryParam("articleids", String.join(",", articleids));
URI uri = builder.build().encode().toUri();
It forms the URL like:
https://10.0.3.2:5000/getsubscribedarticles?articleids=123,456,789
I would expect that the correct working url is something like:
https://10.0.3.2:5000/getsubscribedarticles?articleids[]=123&articleids[]=456&articleids[]=789
After a quick look at the code of public UriComponentsBuilder queryParam(String name, Object... values), I would solve it by using UriComponentsBuilder this way:
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("articleids[]", articleids.toArray(new String[0]));
It is important that, the second parameter is an array but not an Object/Collection!
You did everything correct. You just need to call it without the [].
Just invoke it with .../getsubscribedarticles/articleids=foo,bar,42
I tested this with Spring Boot 1.2.6 and it works like this.
Thanks to dOx for his suggestion - I managed to solve this with the PathVariable - i set the list in my url for android:
final String url = "https://10.0.3.2:5000/getsubscribedarticles/"+new ArrayList<>(articleids);
For my rest server:
#RequestMapping(value = "/getsubscribedarticles/[{articleids}]", method = RequestMethod.GET)
public List<Posts> getSubscribedPostFeed(#PathVariable String[] articleids){
}
I'm creating a REST Client in Java with RestTemplate from Spring Framework.
Everything is fine until i have to do a post with postForLocation.
The webservice i'm having access return a json with informations about the POST ACTION.
In PHP it's fine but i really don't understand how to do in Java with RestTemplate.
public String doLogin()
{
Map<String, String> args = new HashMap<String, String>();
args.put("email", AUTH_USER);
args.put("token", AUTH_PASS);
String result = restTemplate.postForLocation(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
return result;
}
This returns NULL.
With same code but using getForObject (and of course, changing the URL to something right) I have a full response, i.e. this works:
String result = restTemplate.getForObject(url, String.class);
So... how get the RESPONSE from a postForLocation?
Obs.: Sorry if this question is dumb. I'm beginner in Java
The postForLocation method returns the value for the Location header. You should use postForObject with the String class, which returns the server's response.
So like this:
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email={email}&token={token}", String.class, args);
This will return the response as a string.
Thanks to one of answers i've figured out how get the response from a POST with Spring by using the postForObject
String result = restTemplate.postForObject(API_URL + "account/authenticate/?email="+ AUTH_USER +"&token="+ AUTH_PASS, null, String.class);
For some reason i can't use arguments with MAP and have to put them inline in URL. But that's fine for me.