RestTemplate uriVariables not expanded - java

I try to access a rest endpoint by using springs RestTemplate.getForObject() but my uri variables are not expanded, and attached as parameters to the url. This is what I got so far:
Map<String, String> uriParams = new HashMap<String, String>();
uriParams.put("method", "login");
uriParams.put("input_type", DATA_TYPE);
uriParams.put("response_type", DATA_TYPE);
uriParams.put("rest_data", rest_data.toString());
String responseString = template.getForObject(endpointUrl, String.class, uriParams);
the value of the endpointUrl Variable is http://127.0.0.1/service/v4_1/rest.php and it's exactely what it's called but I'd expect http://127.0.0.1/service/v4_1/rest.php?method=login&input_type... to be called.
Any hints are appreciated.
I'm using Spring 3.1.4.RELEASE
Regards.

There is no append some query string logic in RestTemplate it basically replace variable like {foo} by their value:
http://www.sample.com?foo={foo}
becomes:
http://www.sample.com?foo=2
if foo is 2.

The currently-marked answer from user180100 is technically correct but not very explicit. Here is a more explicit answer, to help those coming along behind me, because the answer didn't quite make sense to me at first.
String url = "http://www.sample.com?foo={fooValue}";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("fooValue", "2");
// "http://www.sample.com?foo=2"
restTemplate.getForObject(url, Object.class, uriVariables);

Related

SpringBoot: How to send and access HashMap <String,String> passed through a RestTemplate HttpGet Request?

I am new to SpringBoot and trying to figure out few things. I am sending HashMap as a part of the RestTemplate HttpMethod.GET call. My question, Is the way I am sending the HashMap as part of the request is correct and if so how do we access the HashMap values from the MicroService2?
MicroService 1
Map<String, String> map=new HashMap<>();
map.put("name", "abc");
HttpEntity<Map<String, String>> entity=new HttpEntity<>(map, headers);
restTemplate.exchange("http:localhost:8080/getdata", HttpMethod.GET, entity , Object.class);
Now how to get the values of the HashMap passed from the MicroService 1.
MicroService 2
#GetMapping("/getdata")
Object getData(#RequestParam HashMap<String,String> user){
sysout(user) // Null
}
I have tested below solution on my machine and its working. You need to pass information in query params as shown in below example:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
header.add("headerName", "headerValue");
HttpEntity<String> entity = new HttpEntity<>(header);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString("http://localhost:8080/getdata");
//add data as a query params
uriComponentsBuilder.queryParam("name", "abc");
restTemplate.exchange(uriComponentsBuilder.toUriString(), HttpMethod.GET, entity , Object.class);
It's not correct. In controller method you should pass Map interface instead of HashMap implementation, also you should use the same approach when you declare variables I mean:
Map<String,String> map=new HashMap<>() instead of HashMap<String,String> map=new HashMap<>();

Issue with uriVariable in RestTemplate.exchange method [duplicate]

I try to access a rest endpoint by using springs RestTemplate.getForObject() but my uri variables are not expanded, and attached as parameters to the url. This is what I got so far:
Map<String, String> uriParams = new HashMap<String, String>();
uriParams.put("method", "login");
uriParams.put("input_type", DATA_TYPE);
uriParams.put("response_type", DATA_TYPE);
uriParams.put("rest_data", rest_data.toString());
String responseString = template.getForObject(endpointUrl, String.class, uriParams);
the value of the endpointUrl Variable is http://127.0.0.1/service/v4_1/rest.php and it's exactely what it's called but I'd expect http://127.0.0.1/service/v4_1/rest.php?method=login&input_type... to be called.
Any hints are appreciated.
I'm using Spring 3.1.4.RELEASE
Regards.
There is no append some query string logic in RestTemplate it basically replace variable like {foo} by their value:
http://www.sample.com?foo={foo}
becomes:
http://www.sample.com?foo=2
if foo is 2.
The currently-marked answer from user180100 is technically correct but not very explicit. Here is a more explicit answer, to help those coming along behind me, because the answer didn't quite make sense to me at first.
String url = "http://www.sample.com?foo={fooValue}";
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("fooValue", "2");
// "http://www.sample.com?foo=2"
restTemplate.getForObject(url, Object.class, uriVariables);

RapidApi Android

I am messing around with RapidAPI and i dont undertand the code they give.
Could someone give me a teardown? It says in order to access api i have to write the following code
Map<String, Argument> body = new HashMap<String, Argument>();
body.put("ParameterKey1", new Argument("data", "ParameterValue1"));
body.put("ParameterKey2", new Argument("data", "ParameterValue2"));
try {
Map<String, Object> response = connect.call("APIName", "FunctionName", body);
if(response.get("success") != null) { }
what are parameter keys 1 and 2, the data, and the parameter values
edit1:this is the code snippet i want to use in android studio
HttpResponse<JsonNode> response = Unirest.get("https://spoonacular-recipe-
food-nutrition-v1.p.mashape.com/recipes/search?
diet=vegetarian&excludeIngredients=coconut&instructionsRequired=
false&intolerances=egg%2C+gluten&limitLicense=false&number=
10&offset=0&query=burger&type=main+course")
.header("X-Mashape-Key",
"Xxxxxx")
.header("X-Mashape-Host", "spoonacular-recipe-food-nutrition-
v1.p.mashape.com")
.asJson();
Your example code is using this https://github.com/zeeshanejaz/unirest-android. If you want to use that snippet you could start with that.

What is the best way to pass multiply parameters as one http query parameter?

I have java web application (servlet) that does user authentication using SalesForce Server OAuth Authentication Flow. This OAuth Authentication provides "state" query parameter to pass any data on callback. I have a bunch of parameters that I want to pass through this "state" query param. What is the best way to do it? In java in particularly?
Or in other words, what is the best way to pass an array or map as a single http query parameter?
You can put all in json or xml format or any other format and then encode in base64 as a one large string. Take care that params can impose some hard limit on some browser/web server.
So, I have done it this way. Thank you guys! Here are some code snippets to illustrate how it works for me:
// forming state query parameter
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("1", "111");
stateMap.put("2", "222");
stateMap.put("3", "333");
JSONObject jsonObject = new JSONObject(stateMap);
String stateJSON = jsonObject.toString();
System.out.println("stateJSON: " + stateJSON);
String stateQueryParam = Base64.encodeBase64String(stateJSON.getBytes());
System.out.println("stateQueryParam: " + stateQueryParam);
// getting map from state query param
ObjectMapper objectMapper = new ObjectMapper();
stateMap = objectMapper.readValue(Base64.decodeBase64(stateQueryParam.getBytes()), LinkedHashMap.class);
System.out.println("stateMap: " + stateMap);
Here is output:
stateJSON: {"1":"111","2":"222","3":"333"}
stateQueryParam: eyIxIjoiMTExIiwiMiI6IjIyMiIsIjMiOiIzMzMifQ==
stateMap: {1=111, 2=222, 3=333}

Spring Social Facebook - publish/post API details

I have been looking into Spring Social Facebook's publish(objectId, connectionName, data) API, but am not sure of the usage of this API (sadly, due to lack of javadocs!). Can someone point me to a comprehensive sample usage of the API, please?
What I am looking to do is publish a story on a user's wall, similar to the below snapshot:
How should the publish() API be used to do the same? Any help is highly appreciated!
Also, I need my post to have additional actions (apart from Like, Comment).
The link given by you already having a lot documentation for method.
Find one example with flow of publish(objectId, connectionName, data) here
Also see many examples for at github-SpringSource for additional actions including publish(objectId, connectionName, data).
Update:
You might get some help from this method:
public void postToWall(String message, FacebookLink link) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("link", link.getLink());
map.set("name", link.getName());
map.set("caption", link.getCaption());
map.set("description", link.getDescription());
map.set("message", message);
publish(CURRENT_USER, FEED, map);
}
Here's what I could finally figure out:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("link", linkUrlString);
map.set("name", "Link Heading");
map.set("caption", "Link Caption");
map.set("description", "Loooooo....ng description here");
map.set("message", "hello world");
// THE BELOW LINES ARE THE CRITICAL PART I WAS LOOKING AT!
map.set("picture", "http://www.imageRepo.com/resources/test.png"); // the image on the left
map.set("actions", "{'name':'myAction', 'link':'http://www.bla.com/action'}"); // custom actions as JSON string
publish(userIdToPostTo, "feed", map);
Like above answer but I use post for my solution. See this:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map1.set("link", "https://www.facebook.com/profile.php?id=100006216492034");
map1.set("name", "Project Test Post to Group");
map1.set("caption", "Please ignore this Post");
map1.set("description", "YOLO here is my discription, Please ignore this post");
facebook.post("userId or GroupID", "feed", map);

Categories