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.
Related
I have to call a DELETE Method inside one of the APIS of a client.
This shouldn´t be a problem but I am struggling with the framework that my company currently uses and I hope I can get some info that hopefully will help me solve the problem:
First thing first.
1: The api doesn´t work if I do the call sending the params as URL:
2: It works completely OK if I send the params inside the body as x-www-form-urlencoded but not form-data or raw
The documentation of the method inside the API told us the following: (Important to Look to IDEtapa)
I have to do this call in JAVA (JAVA 8)
currently my company uses HTTP_CLIENT as the main framework for APICalls.
My code:
The build of the Data (Currently I build both, as Entity and as Params for you to view I´ve tried with each one of them indepently):
Map datosApi = new HashMap<>();
datosApi.put(Constants.URL, anular_cita);
Map headers = new HashMap<>();
headers.put(Constants.AUTHORIZATION, params.get("token_autorizacion"));
headers.put("Content-Type", "application/json");
headers.put("entity_charset", "UTF-8");
datosApi.put(Constants.HEADERS, headers);
JSONObject entity = new JSONObject();
Map param = new HashMap();
param.put(Constants.ID_CENTRO, consul);
param.put("IdAsistencia", propiedades[0]);
param.put("IdCapitulo", propiedades[1]);
param.put("IdEtapa", Integer.valueOf(propiedades[2]));
entity.put(Constants.ID_CENTRO, consul);
entity.put("IdAsistencia", propiedades[0]);
entity.put("IdCapitulo", propiedades[1]);
entity.put("IdEtapa", Integer.valueOf(propiedades[2]));
datosApi.put("entity", entity.toString());
datosApi.put("entity_mime_type", "application/json");
datosApi.put("entity_charset", "UTF-8");
datosApi.put("params", param);
String anularCita = APIDao.callAPIDelete(datosApi);
The preparation for my call to the framework:
public static String callAPIDelete(Map in) {
String contentString = "";
Map res = new HashMap<>();
try {
res = XWM.execute("delete#http_client", in);
byte[] content = (byte[]) res.get("content");
contentString = new String(content, StandardCharsets.UTF_8);
And inside our framework we have this:
if (StringUtils.equals(StringUtils.trim(method), "delete"))
{
StringBuilder requestUrl = new StringBuilder(url);
if (formparams != null)
{
if (requestUrl.indexOf("?")==-1) requestUrl.append("?");
else requestUrl.append("&");
requestUrl.append(URLEncodedUtils.format(formparams, charset));
}
if (entityRequest != null)
{
log.error("Param 'entity' no puede usarse en get (se ignora)");
}
HttpDelete delete = new HttpDelete(requestUrl.toString());
delete.setConfig(requestConfig);
uriRequest = delete;
}
}
}
}
// Headers
if (headers != null)
{
for (String h: headers.keySet()) uriRequest.addHeader(h, headers.get(h));
}
// Ejecutamos método
log.info("Executing request " + uriRequest.getRequestLine());
CloseableHttpResponse response = null;
if (!preemtiveAuth || credsProvider == null)
{
response = httpclient.execute(uriRequest);
}
As you can see, in the delete method, we ignore the entity that i´ve built in the first patch of code.
The HTTPDelete Class is APACHE, the url with info of the class is the following:
https://www.javadoc.io/doc/org.apache.httpcomponents/httpclient/4.5.2/org/apache/http/client/methods/HttpDelete.html
The question can be divided in two:
1: Can we send the Entity in a Delete Call? I have found a few info about this in the following places:
Is an entity body allowed for an HTTP DELETE request?
https://web.archive.org/web/20090213142728/http://msdn.microsoft.com:80/en-us/library/cc716657.aspx
https://peterdaugaardrasmussen.com/2020/11/14/rest-should-you-use-a-body-for-your-http-delete-requests/
I assume that in order to do it, i would need a new HttpDelete that would allow us to use entity, if possible, could you give me some examples of this?
2: For what i understand of the links i posted above, while using entity in Delete calls is not forbidden is something that is not encouraged, Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params? (It is not personal or sensible info, just a bunch of IDs)
Thank you so much for your attention and my apologies for any typo or format mistake, still learning how to make good posts.
EDIT: i have found this answer setEntity in HttpDelete that more or less solve the first issue about if its, posible to send an Entity in a Delete call, but still, don´t now if it should be better to ask them to change their method
As told in the coments by Ewramner and VoiceOfUnreason and in the edits:
1: The answer about how to make this was found in an older post of StackOverflow: setEntity in HttpDelete
2: The answer about "Should I just talk with the people who made the API and ask them to change their configuration to allow us to send the info by params?" was answered by both of them. While it´s not forbidden, it´s something thats not recommended.
My course of action will be:
1: Talk with the people responsible for the API to give them info about this situation.
2: Ask our Architecture team to create a new method that will allow us to do HttpDelete calls with an entity body, just in case that we have to make more API calls like this one.
With this i think all my answers are solved.
Again, Thank you.
I'm a beginner in Android. I'm trying to communicate using Retrofit. The problems I faced were as follows. You are trying to send multiple queries to the server as follows: Other queries fly well, but the hashmaps do not deliver normally. Please help me to solve the problem that I've encountered.Help Me!
android retrofit.java code
#GET("product_option.php")
Call<ResponseBody> request_detail_category_product_information1(
#Query("option") String filter_option,
#Query("page") String page,
#Query("fitme") String fitme,
#Query("body_information") Map<String, String>HashMap
);
php code
$option = $_GET['option'];
$now_page = $_GET['page'];
$fitme = $_GET['fitme'];
$body_information = $_GET['body_information'];
if($body_information){
$shoulder = $body_information['shoulder'];
$chest = $body_information['chest'];
$waist = $body_information['waist'];
$hip = $body_information['hip'];
$thigh = $body_information['thigh'];
}
You can use multiple query params with #QueryMap annotation instead of #Query.
#QueryMap Map<String, String> queryParams
Then you can access it in php.
$_GET['shoulder'];
$_GET['chest'];
example
I've been to asked to refactor some code that makes a request to a web API that I have no idea what happens when it receives the request. I just have to clean up the code that makes the request. I now have this:
FormBody formBody = new FormBody.Builder()
.add("task", task.get("task"))
.add("status", task.get("status"))
.add("spent_time", task.get("spentTime"))
.add("impediments", task.get("impediments"))
.add("reoccurring", String.valueOf(task.get("reoccurring")))
.build();
return new OkHttpClient().newCall(
new Request.Builder()
.url(buildUrl("/activities/" + task.get("id")))
.method("POST", formBody)
.header("Accept", "application/json")
.build()
Originally, this function was split into three more functions.
One url call for having the forms task and status
another url call for having spent_time and impediments
and then another url call for only having reoccurring
But since they all belong to the same url, I've decided to combine them into one function because I had an idea. Though it seems my idea kinda falls short. How do I make it so that if (e.g.) task,status, and reoccurring are null, then it would only create a form that only has spent_time and impediments?
It looks like your task variable is a map of some sorts that has String keys and Object values. Here is your solution:
Builder builder = new FormBody.Builder();
String[] names = { "task", "status", "reoccurring", "spent_time", "impediments" };
for (String name : names) {
Object value = task.get(name);
if (value != null)
builder.add(name, value instanceof String ? (String) value : String.valueOf(value));
}
FormBody formBody = builder.build();
This iterates through all your form keys and checks whether the values are null or not before adding them to your form builder.
If you want you can change this to use Streams, which might be more efficient and shorter.
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>>>{});
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);