Issue with uriVariable in RestTemplate.exchange method [duplicate] - 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

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}

how to manipulate HTTP json response data in Java

HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);
entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
Output as follows in json format
----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------
What I want to know is how to you can manipulate this data using Java without writing it to a file?
I want to print name, value in my code
Jackson library is preferred but any would do.
thanks in advance
You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :
JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj = json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));
You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.
May this will help you.
Here's two ways to do it without a library.
NEW (better) Answer:
findInLine might work even better. (scannerName.findInLine(pattern);)
Maybe something like:
s.findInLine("{"session":{"name":"(\\w+)","value":"(\\w+)"},"loginInfo":{"loginCount":(\\d+),"previousLoginTime":"(\\w+)"}}");
w matches word characters (letters, digits, and underscore), d matches digits, and the + makes it match more than once (so it doesnt stop after just one character).
Read about patterns here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
OLD Answer:
I'm pretty sure you could use a scanner with a custom delimiter here.
Scanner s = new Scanner(input).useDelimiter("\"");
Should return something like:
{
session
:{
name
:
JSESSIONID
,
value
:
5F736EF0A08ACFD7020E482B89910589
And so on. Then just sort through that list/use a smarter delimiter/remove the unnecessary bits.
Getting rid of every other item is a pretty decent start.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html has info on this.
I higly recomend http-request built on apache http api.
private static final HttpRequest<Map<String, Map<String, String>>> HTTP_REQUEST = HttpRequestBuilder.createGet(yourUri, new TypeReference<Map<String, Map<String, String>>>{})
.addDefaultHeaders(headers)
.build();
public void send(){
ResponseHandler<Map<String, Map<String, String>>> responseHandler = HTTP_REQUEST.execute();
Map<String, Map<String, String>> data = responseHandler.get();
}
If you want use jackson you can:
entity = httpResponse.getEntity();
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, String>> data = mapper.readValue(entity.getContent(), new TypeReference<Map<String, Map<String, String>>>{});

RestTemplate uriVariables not expanded

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

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