drakma: How to pass JIRA API token for requests? - common-lisp

When I do the following, passing my JIRA API token ...
curl --verbose --request GET \
--url 'https://myJira.atlassian.net/....' \
--user 'my_email#domain.com:my_jira_api_token' ...
... the operation succeeds and I see one of the headers was:
Authorization: Basic encodedAuthInfoHere
How would I do the same with Drakma? :basic-authorization takes a list of username and password. But JIRA says basic auth has been deprecated.
(drakma:http-request url
:method :get
:basic-authorization '(email passwd)
...
Is there a way to perform the same encoding that curl used, and add the header explicitly when calling http-request? Thanks in advance!

Like for curl, Drakma's password can be whatever you want it to be, so you can insert the jira token as in you did with curl.
Would
(setf drakma:*header-stream* *standard-output*)
(drakma:http-request "https://myJira.atlassian.net/...."
:method :get
:basic-authorization '("my_email#domain.com" "my_jira_api_token"))
spark joy?
I'd expect drakma to create a string my_email#domain.com:my_jira_api_token, base64-encode it,
and append it to "Authorization: Basic ",
so you'd get a header like this:
Authorization: Basic bXlfZW1haWxAZG9tYWluLmNvbTpteV9qaXJhX2FwaV90b2tlbg==
If your curl example is complete, Drakma should get you as far as curl does.

You can pass :parameters to the request:
USER> (drakma:http-request "http://example.com"
:method :get
:parameters '(("user" . "token")))
The reply is:
"<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" conten...[sly-elided string of length 1256]"
200 (8 bits, #xC8, #o310, #b11001000)
((:AGE . "507992") (:CACHE-CONTROL . "max-age=604800")
(:CONTENT-TYPE . "text/html; charset=UTF-8")
.....)
#<URI http://example.com/?user=token>
#<FLEXI-STREAMS:FLEXI-IO-STREAM {101D4A3723}>
T
"OK"
In particular, the 4th returned value, the URI the reply comes from, is:
http://example.com/?user=token

Related

Not able to get http response from a third party API when code deployed to azure function app, in debug mode its working fine

I have created an azure http trigger (also tried with timer trigger) function and it is calling an third party API with necessary params as content header. Locally in VS Code (debug mode), it's working fine. I am getting desired response (getting token if we call token end point as well as proper response if we call another end point by passing token). Even with postman I am getting correct response.
But when I deployed this function to azure function app, it's not getting response from both endpoint. (either from token one or if I pass hardcoded token copied from postman to second endpoint).
In logs, I can see function being called and when I am logging response I am getting a large html text(don't know what is that)
Is it possible that third party API is blocking or restricting calls from azure function(though it's working locally or with postman if we pass proper values)
Tried everything but can' find out the exact issue. I have verified I am passing correct values as grant_type, client_Id, client_secret, username, password, scope)
Have pasted below sample piece of code:
private async Task<Token> GetToken()
{
try{
HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", Environment.GetEnvironmentVariable("test-grant-type")},
{"username", Environment.GetEnvironmentVariable("test-username")},
{"password", Environment.GetEnvironmentVariable("test-password")},
{"client_id", Environment.GetEnvironmentVariable("test-client-id")},
{"client_secret", Environment.GetEnvironmentVariable("test-client-secret")},
{"scope", Environment.GetEnvironmentVariable("test-scope")}
});
HttpClient client = new HttpClient();
string tokenEndPoint = Environment.GetEnvironmentVariable("test-tokenApiEndPoint");
//calling API
HttpResponseMessage messageResult = await client.PostAsync(tokenEndPoint, content);
_logger.LogInformation($"Log Info: GetToken method: httpResponseMsg: {messageResult}");
string apiResponse = messageResult.Content.ReadAsStringAsync().Result;
_logger.LogInformation($"Log Info: GetToken method: apiResponse: {apiResponse}");
Token resTokenModel = JsonConvert.DeserializeObject<Token>(apiResponse);
}
catch (System.Exception ex)
{
_logger.LogError($"Exception : GetToken Method: Exception: {ex.Message}");
throw new Exception(ex.Message);
}
return resTokenModel;
}
Log html response sample (it's not complete as it is very large), Log1:
2022-06-29T08:30:05.490 [Information] Log Info: GetToken method: httpResponseMsg: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:{Cache-Control: no-store, no-cachePragma: no-cacheStrict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffX-Frame-Options: DENYLink: <https://aadcdn.msauth.net>; rel=preconnect; crossoriginLink: <https://aadcdn.msauth.net>; rel=dns-prefetchLink: <https://aadcdn.msftauth.net>; rel=dns-prefetchX-DNS-Prefetch-Control: onP3P: CP="DSP CUR OTPi IND OTRi ONL FIN"x-ms-request-id: 18670f19-3bec-4556-9b66-2c3760855300x-ms-ests-server: 2.1.13006.6 - WEULR1 ProdSlicesX-XSS-Protection: 0Set-Cookie: buid=0.AQIANaKxxxx_PBbRZsxxxx_PzErkPdDcCAdAA.xxxx--DLA3VO7QrddgJg7WevrDRjJU0T4KWPoylW2bC-ExpJHweIFWSInAdxjVwFITAQNF_FKbJPKHxxxxxp9ivEPYDacemz4wUo_sc04zyJbXjfz-2bVvxUz-AgAA; expires=Thu, 28-Jul-2022 08:30:05 GMT; path=/; secure; HttpOnly; SameSite=NoneSet-Cookie: fpc=AsZ-7OJNXMJAsZa7WVUJsyzxSauWAQAAAAyzTNoOAAAA; expires=Thu, 29-Jul-2022 08:30:05 GMT; path=/; secure; HttpOnly; SameSite=NoneSet-Cookie: esctx=AQABAAAAAAD--DLA3VO7QrddgJg7WevrvlcjjHs6JSFKoM9RHgIe1sGicQYOARxxxxwtTCtFHUZ7DawxrkQC4x3uxxkXSFkTTUgthZA1MEqk-Pmv2mzfkL9xBHg1V-LSzxeaWxtB38SA--OJKRBbdBVRR0D80RGqwGWTn5bm4XeaaWFCt5SYYet_q1fuHwxUMe7OXIuQgAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly; SameSite=NoneSet-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; httponlySet-Cookie: stsservicecookie=estsfd; path=/; secure; httponlyDate: Tue, 28 Jun 2022 08:30:04 GMTContent-Type: text/html; charset=utf-8Expires: -1Content-Length: 195652}
from below html, I can only understand "Sign in to your account" but where to sign, Log2:
2022-06-28T08:30:05.492 [Information] Log Info: Synergi Repo: GetToken method: apiResponse:<!-- Copyright (C) Microsoft Corporation. All rights reserved. --><!DOCTYPE html><html dir="ltr" class="" lang="en"><head><title>Sign in to your account</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes"><meta http-equiv="Pragma" content="no-cache"><meta http-equiv="Expires" content="-1"><link rel="preconnect" href="https://aadcdn.msauth.net" crossorigin><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="//aadcdn.msauth.net"><link rel="dns-prefetch" href="//aadcdn.msftauth.net"><meta name="PageID" content="ConvergedSignIn" /><meta name="SiteID" content="" /><meta name="ReqLC" content="1033" /><meta name="LocLC" content="en-US" /><meta name="referrer" content="origin" /><meta name="format-detection" content="telephone=no" /><noscript><meta http-equiv="Refresh" content="0; URL=https://login.microsoftonline.com/jsdisabled" /></noscript><meta name="robots" content="none" /><script type="text/javascript">//<![CDATA[$Config={"fShowPersistentCookiesWarning":false,"urlMsaSignUp":"https://login.live.com/oauth20_authorize.srf?response_type=code\u0026client_id=5xxx2-085c-xxxx-bf88-xxxxx8\u0026scope=openid+profile+email+offline_access\u0026response_mode=form_post\u0026redirect_uri=https%3a%2f%2flogin.microsoftonline.com%2fcommon%2ffederation%2foauth2msa\u0026state=rQQIxxxxxxFM4lbVARUISEBAuDmwnlYp99Z8dGDEFtIWogJQGEUCQ4n-_SE845sZ2UgBj5GZkYChISYycEC3QBJIREp0wIMSPBABJbO-KUFYnlLe99f-87Wxxxxkk1A8g9i0b-pawoLCQ6buGcLDlxEf2H_549xxxxvH95ugLnroRzxCot6m-DEWpr2E0_Xk7HicVcOaIUPhlJF8XSvvwZgAsAPADbzJYdaFAufQMQtA2LmBpASIaAgriAkEAjR6tf8fLM2TNfM6YhieZtvFB7ka_3-ahzdGrdTmnLvjlZXIxrK4FJ0k6sWT-Ox5qlhGJa1enI-iYRPNU_QMOFlrRnLrlQ0bNH1y3Goedpfux2982_DHb2puAy4SmU67ugsUoqztKOnUxxxxx4PMkZs0Sp1GIaYZy_EJnGgbwgTWowz5mAfE-FmyDZPEhmpPYiDGEKE2dCx7QzCmAt9GhjQtlwR2Dwj84V2d2FJBU2xl3mVxrS38LJQsijF1LQI9G1uQlwNCHSRS6AjmDBIpuX6xnahGPW5ksGXApjMgN0Z8Hw26_H4fPfYz1NXlp6IsnPjXju3PasnA0MuXsNdtFLt9thyO0zZsoqvxiuN9bONOg4vLEbDxsUzdnVQO4089KgIfhfBw325rbn_1P7iAHh3MLd7aOfbqzf3nz7-de4P0\u0026estsfed=1\u0026uaid=71c115c676664cc9bad0639fd6e7c4bf\u0026signup=1\u0026lw=1\u0026fl=easi2\u0026fci=7e7dac8e-5abd-4b36-b3f3-f312b90f7437","urlMsaLogout":"https://login.live.com/logout.srf?iframed_by=https%3a%2f%2flogin.microsoftonline.com","urlOtherIdpForget":"https://login.live.com/forgetme.srf?iframed_by=https%3a%2f%2flogin.microsoftonline.com","showCantAccessAccountLink":true,"urlGitHubFed":"https://login.live.com/oauth20_authorize.srf?response_type=code\u0026client_id=xxx-085c-xx-bf88-xxx\u0026scope=openid+profile+email+offline_access\u0026response_mode=form_post\u0026redirect_uri=https%3a%2f%2flogin.microsoftonline.com%2fcommon%2ffederation%2foauth2msa\u0026state=rQQIAxxxVE9bNNAxxxISEBAuDmwnlYp99Z8dGDEFtIWogJQGEUCQ4n-_SE845sZ2UgBj5GZkYChISYycEC3QBJIREp0wIMSPBABJbO-KUFYnlLe99f-87WUAV5JUc7gSUVTkxxxx-pawoLCQ6buGcLDlxEf2H_549P1AjD41tibs2efvH95ugLnroRzxCot6m-DEWpr2E0_Xk7HicVcOaIUPhlJF8XSvvxxxbzJYdaFAxxxxxiAkEAjR6tf8fLM2TNfM6YhieZtvFB7ka_3-ahzdGrdTmnLvxxxrK4FJ0k6sWT-Ox5qlhGJa1enI-iYRPNU_QMOFlrRnLrlQ0bNH1y3Goedpfux2982_DHb2puAy4SmU67ugsUoqztKOnUymtrLWyW56kmRshQ14PMkZs0Sp1GIaYZy_EJnGgbwgTWowz5mAfE-FmyDZPEhmpPYiDGEKE2dCx7QzCmAt9GhjQtlwR2xxxxd2FJBU2xl3mVxrS38LJQsijF1LQI9G1uQlwNCHSRS6AjmDBIpxxxxsGXApjMxxx26_H4fPfYz1NXlp6IsnPjXju3PasnA0MuXsNdxxxvxiuN9bONOg4vLEbDxsUzdnVQO4089KgIfhfBw325rbn_1P7iAHh3MLd7aOfbqzf3nz7-de4P0\u0026estsfed=1\u0026uaid=71c115c676664cc9bad0639fd6e7c4bf\u0026fci=7e7dxxxx-b3f3-f312b90f7437\u0026idp_hint=github.com","fShowSignInWithGitHubOnlyOnCredPicker":true,"fEnableShowResendCode":true,"iShowResendCodeDelay":90000,"sSMSCtryPhoneData":"AF~Afghanistan~93!!!AX~Åland Islands~358!!!AL~Albania~355!!!Islands~358!!!AL~Albania~355!!!
---------
-- and so here is large html content as above ---
--------------------------------------------------------------------------------------------------
Exception log:
This is because in code we are parsing response (so below issue is because it tried to parse response html) - so this does not seems to be useful
2022-06-29T15:18:14.657 [Error] Exception : GetToken Method: Exception: Unexpected character encountered while parsing value: '<'. Path '', line 0, position 0.
2022-06-29T15:18:14.710 [Error] Exception : Method: Exception: One or more errors occurred. (Unexpected character encountered while parsing value: '<'. Path '', line 0, position 0.)
If anyone has faced similar issue or can give an idea what can be the cause, though it's hard to find just looking in to code
Thanks
Errors like "Unexpected character encountered while parsing value: '<'. Path '', line 0, position 0." are almost invariably JSON parse errors.
The most common reason for it to occur is when the string being deserialized is not actually valid JSON.
Also check if the file containing JSON string had [BOM - Byte Order Mark]. Try and remove the BOM to resolve the error.
Thanks to all who replied and viewed this thread.
We have found the actual problem and it's not from the code/development side. The vendor has migrated the API to azure server and now they have another level of authentication (might be azure Ad)
So the original authentication which I believes (JWT Oauth) is returning it's token but we are not authenticating azure one so that's might be the reason we are getting azure html page.
Now API team is looking what's need to be done. We can close this thread or if someone has any solution or suggestion they can share.
Thanks

How to correctly make a POST request to a form login and get the session-token?

I'm building a web crawler to scrape an web page information that are behind a authentication login form. So I need to login in the app with a bare HTTP request first to be able to scrape needed info.
As I know, the script need to send a POST request with login params urlencoded in addition with the csrf-token and also a unauthenticated session-cookie as a cookie header, right?
The app that I'm trying to scrape is: https://app-sandbox.kobana.com.br
Taking a look on GET request headers/body of the login page I got:
a meta tag with name csrf-param with content set to authenticity_token
a meta tag with name csrf-token and it's content
a hidden input tag with name authenticity_token and it's content
a unauthenticated session-token that can be retrieved from set-cookie header
When I do a POST request on browser, what is sent is this authenticity_token and a cookie header with multiples cookies values that I can't find in any request/response header.
So I tried to reproduce this login flow with cURL and after of send correct body/headers I receive a 302 response, which is ok. But following the redirect link I get a not_found 404 response.
I also tried to follow this flow with insomnia/postman but in this case I have a success login.
My actual code to retrieve the authenticated session-token is:
defmodule KobanaBrowserClient do
defp base_url, do: "https://app-sandbox.kobana.com.br"
defp sign_in_path, do: base_url() <> "/users/sign_in"
def sign_in(body, cookie) do
HttpClient.post(build_client(), sign_in_path(), body, headers: [{"cookie", cookie}])
end
def get_session_cookie(email, password) do
{:ok, response} = get_sign_in_page()
# Extrai o cookie não autenticado a partir do Headers
cookie = parse_session_cookie(response.headers)
{:ok, document} = Floki.parse_document(response.body)
# Extrai o token CSRF do body da requisição
authenticity_token =
document
|> Floki.find(~s(form input[name="authenticity_token"]))
|> Floki.attribute("value")
|> Floki.text()
req_body = %{
"user[email]" => email,
"user[password]" => password,
"user[remember_me]" => 0,
"authenticity_token" => authenticity_token
}
{:ok, login_response} = sign_in(req_body, cookie)
parse_session_cookie(login_response.headers)
end
def parse_session_cookie(headers) do
headers
|> Enum.reduce("", fn
{"set-cookie", cookie}, acc -> acc <> " " <> cookie
_, acc -> acc
end)
|> String.trim()
end
end
And the cURL command generated by insomnia is:
curl --request POST \
--url https://app-sandbox.kobana.com.br/users/sign_in \
--header 'Content-Type: application/x-www-form-urlencoded' \
--cookie '_boletosimples_session=eaI6y7pJ1%252BHj0CyC3%252BgWE%252FCEYV4K5mFoYANYKXCasH1LvhrmShvZUGdeYJQo3QCSXC%252FTU9s4V77Csc82FsOhX8bJz%252F%252BVRSvMKFa2I%252BHV4Nu5OeeIA9fXzooRSljtik9SvKD3of1dVY68EZXe67mXberh2i0P1eemc2ixS0Zp%252FWhaxQr7o1BOKJVL6EARV2uUL7hfwWg58z%252BHmkAZ2eGpHwrWESOuR7ALc8X%252Fk5l35RVeKIsbbcduxFqsQlh4olBJ8gxYNQVZXPy1p1VTvrMN8yGhlPGbFxzCJG4hScYMneB0Ph4%252Ba5HFA0F84hd%252FOeiWjCPTkeDDNcajHgaH8YI6grWRfS42AEziRLK6VnQuZtROue%252FNIgn%252BeCqwofW%252BdMrpbvppbc19uEWxhDCrzvit0Cc7aE1LltUzlAWJmIlrNXxUJlN7JM%252FJGL6AoMe4iYyj7%252BbRasuQ%252B9WQRycVYK%252Bxe40ZG6DqjY7wolBxw%252FC6mAoWpHyYv696UUoV1uFQahK%252BbOad8nQ9Myhvj3iFPaV3isqMMdlTWaQIEjOkgLT13dXVUxSLcrT62VtZC%252Fa5jSo31%252FDxmFfEQZv0zlW8e3eJ%252BpgPeUWBWRc%252BUMiJDMPQ1sDknka2w4gMAGRna0B7IoIxG38vkFwAQ3Ob8wPn6t4SU%252FfgZkCjmjggxs87GNXyaZjHqVyYjIr4IIODiwd9kRo1FATu%252Bms516lhNi3aF1wFqZyWS46yMlq0ZlUDSFXFI73U1ggswN2DIeOmFGBiw6ZoW%252B8CEWrZ0QOHXAyyMVGI8FL1FtaHnBp0prmvW88I--FAwVzHnQF%252BJg4NJ0--uTpgEAZoQEQdp%252BBHaJMU%252BQ%253D%253D; user.id=eyJfcmFpbHMiOnsibWVzc2FnZSI6Ik1qZzJOZz09IiwiZXhwIjpudWxsLCJwdXIiOiJjb29raWUudXNlci5pZCJ9fQ%253D%253D--4b3f7664fa367f606bcddead8e20c13202cb8415; user.expires_at=eyJfcmFpbHMiOnsibWVzc2FnZSI6IklqSXdNakl0TURNdE1UUlVNVGM2TlRVNk5ETXRNRE02TURBaSIsImV4cCI6bnVsbCwicHVyIjoiY29va2llLnVzZXIuZXhwaXJlc19hdCJ9fQ%253D%253D--5f3bcd28b81d798b5270421b5f4d610b4ec200a1; user_email=eyJfcmFpbHMiOnsibWVzc2FnZSI6IkluWnBkRzl5TG14bFlXeEFjMjlzWm1GamFXd3VZMjl0TG1KeUlnPT0iLCJleHAiOm51bGwsInB1ciI6ImNvb2tpZS51c2VyX2VtYWlsIn19--0e04fcebc5f9ce0acdbe7e92d55c19f28ab37121; user_tracking_uid=eyJfcmFpbHMiOnsibWVzc2FnZSI6IklqazJaVFUzTVRBeExUbGxOVEl0WlRFME55MW1NMlJsTFRjNFl6SmtNREF4TVRFeE1pST0iLCJleHAiOm51bGwsInB1ciI6ImNvb2tpZS51c2VyX3RyYWNraW5nX3VpZCJ9fQ%253D%253D--ee68c7d2dc9f463a4689769a1c4608158ce41463; boletosimples_visitor_guid=96e57101-9e52-e147-f3de-78c2d0011112' \
--data authenticity_token=Dj-_4TVjbSwmDjjorQvI37wMWy5pHmcrVSlkp2EkpojorZiP2a3_AxWiZ47Rkdh3pvoY55j1EIH4z-ze5qUYMg \
--data 'user[email]=account_email' \
--data 'user[password]=account_pass' \
--data 'user[remember_me]=0'
Which fails with a 404 resopnse. What can be happening?

how to execute a https post request using curl in flutter

i am new to using curl and I am trying to execute a https post request using curl. and it doest seem to work like other json post requests so i was hoping someone can explain this to me
I am not sure if i understood your answer well enough but you can take a look at this Package or this one the latter one provides provides more flexibility and features like Interceptors etc.
You can use this package Curl https://pub.dev/packages/curl
example code
import 'package:curl/curl.dart';
import 'package:http/http.dart';
final req1 = new Request("GET", "https://exyui.com/endpoint");
print(toCurl(req1));
// will print out:
// curl 'https://exyui.com/endpoint' --compressed --insecure
final req2 = new Request("PUT", "https://exyui.com/endpoint");
req2.body = "This is the text of body😅, \\, \\\\, \\\\\\";
print(req2);
// will print out:
// curl 'https://exyui.com/endpoint' -X PUT -H 'content-type: text/plain; charset=utf-8' --data-binary \$'This is the text of body\\ud83d\\ude05, \\, \\\\, \\\\\\' --compressed --insecure
final req3 = new Request("POST", "https://exyui.com/endpoint");
final part1 = "This is the part one of content";
final part2 = "This is the part two of content😅";
final expectQuery = "part1=This%20is%20the%20part%20one%20of%20content&part2=This%20is%20the%20part%20two%20of%20content%F0%9F%98%85";
req3.bodyFields = {
"part1": part1,
"part2": part2,
};
print(toCurl(req3));

Cannot make request from GET in R to idealista API

I am trying to make a request from an API of "idealista" (link).
It needs authentication, so what I did was the next:
if(!require("jsonlite")){install.packages("jsonlite")}
if(!require("httr")){install.packages("httr")}
consumer_key <- "my_key"
consumer_secret <- "my_secret"
#Use basic auth
secret <- jsonlite::base64_enc(paste(consumer_key, consumer_secret, sep = ":"))
req <- httr::POST("https://api.idealista.com/oauth/token",
httr::add_headers(
"Authorization" = paste("Basic", gsub("\n", "", secret)),
"Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
),
body = "grant_type=client_credentials"
)
#Extract the access token
token <- paste("Bearer", jsonlite::base64_enc(httr::content(req)$access_token))
So, first: I don't know if the token must to be base64 encoded (I think yes). And I do following to make a request:
url<-"https://api.idealista.com/3.5/es/search?locale=es&maxItems=20&numPage=1&operation=sale&order=publicationDate&propertyType=garages&apikey=my_key&t=1&language=es&bankOffer=true" #an example of url (needs apikey)
req <- httr::GET(url, httr::add_headers("Authorization" = token))
And the response is:
Response [https://api.idealista.com/3.5/es/search?locale=es&maxItems=20&numPage=1&operation=sale&order=publicationDate&propertyType=garages&apikey=80gzxznozajnl3tf30ite86k1p24e4yb&t=1&language=es&bankOffer=true]
Date: 2017-10-10 15:25
Status: 400
Content-Type: text/html
Size: 4.4 kB
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/T...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es_ES" lang="es_ES">
<head>
<title>idealista.com : pisos madrid, pisos barcelona, pisos v...
<meta http-equiv="content-Type" content="text/html; charset=I...
<meta http-equiv="Expires" content="0"/>
<meta name="Pragma" content="no-cache"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache, mustreval...
...
Which does not have sense. Can you tell me what I am doing bad?
The status code that I receive is "400", I do not know what I must to do.
Thanks in advance.
I found a similar question in python and It was solved in the this link
The first part (authentication) was ok but the second one was wrong. Additionally, I tried other url too and the token does not need base64 encoded.
token <- paste("Bearer", httr::content(req)$access_token)
url<-"http://api.idealista.com/3.5/es/search?center=40.42938099999995,-3.7097526269835726&country=es&maxItems=50&numPage=1&distance=452&propertyType=homes&operation=sale"
req <- httr::POST(url, httr::add_headers("Authorization" = token))
As you can see, I was using the function "GET", but watching the python code mentioned above, I used "POST" and it worked!.
I do not know why to use the function POST when I am doing a request but the API works like this.

How do I make curl to POST a parameter, reading its value from a file?

I’m playing with GitHub web hooks and I want to use curl to post some sample JSON. The request is supposed to contain a payload POST parameter with the JSON string as a value. As an example, this works:
$ curl --form payload='{"foo":1}' http://somewhere
But I need to read the JSON from a file (say foo.json). Replacing the JSON string by #foo.json posts the payload in the request body:
--------------------------8d0c6d3f9cc7da97
Content-Disposition: form-data; name="payload"; filename="foo.json"
Content-Type: application/octet-stream
{'foo':1}
--------------------------8d0c6d3f9cc7da97--
That’s not really what I want, I need the payload to be passed as a parameter. How do I do that?
Maybe silly but try this:
cat foo.json | xargs -I % curl --form payload='%' http://example.com
Just wrote this little thing and it worked:
var=`cat some.json` && curl --form payload="$var" http://lvh.me/test/index.php
Here’s an alternative Perl testing script. Pass the target URL as the first argument, feed the JSON to STDIN:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP;
my $target = shift #ARGV or die "Need a target URL";
my $ua = LWP::UserAgent->new;
my $payload = do { local $/; <STDIN> };
my $response = $ua->post($target, { payload => $payload });
print $response->as_string;

Resources