I am obtaining the following response to a HTTP Request in SOAP UI
TTP/1.1 201 Created
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Location: /api/authorization_servers/5362c2c46362f0e7f33379e8
Content-Type: application/json
Transfer-Encoding: chunked
I would like to get the value of 5362c2c46362f0e7f33379e8 in the Location Response Header and transfer it to a Project property called "token". Can someone tell me how I am going to do that?
I am able to get the entire /api/authorization_servers/5362c2c46362f0e7f33379e8 into a variable through Groovy script in this way:
def headerValue = testRunner.testCase.getTestStepByName("Register Authorization Server").httpRequest.response.responseHeaders["Location"]
I am not able to proceed any further. Any help is greatly appreciated!
You have several options if I understand you right.
You could split the value and take the last element:
headerValue = headerValue.split( '/' )[ -1 ]
You could subtract the beginning of the header:
headerValue = headerValue - '/api/authorization_servers/'
Or you could use a regular expression:
headerValue = headerValue.find ~/[a-f0-9]+$/
Related
I'm using RestSharp to consume a PHP based rest API (magento). I'm running into an issue where my request.Content contains a string escaped with backslashes. Like this: "\"mystringIsEscaped\"". It should just be a normal string "mystringIsNotEscaped".
The API does not give double quotes any specific treatment. A JSON response looks like this:
{
"value": 1
}
OR
"SomeValueAsJustString"
Here is my code so far:
// PART 1: Getting an Unauthorized Request Token
var request = new RestRequest("/rest/V1/integration/admin/token", Method.POST);
request.AddJsonBody(new {username = "this.adminUserName", password = "this.adminPassword"});
request.AddHeader("content-type", "application/json");
var _client = new RestClient(_url);
var _jsonSerializer = new JsonSerializer();
_client.AddDefaultHeader(_contentTypeHeaderWithUnderscore ? "Content_Type" : "Content-Type", "application/json");
_client.ClearHandlers(); // http://stackoverflow.com/questions/22229393/why-is-restsharp-addheaderaccept-application-json-to-a-list-of-item
_client.AddHandler("application/json", _jsonSerializer);
var response = _client.Execute(request);
response.Content is double escaped.
My raw response (using fiddler) looks like this:
HTTP/1.1 200 OK
Server: nginx/1.17.1
Date: Mon, 22 Jul 2019 12:38:44 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Set-Cookie: PHPSESSID=873l8qhalaltets0tpa2s2sta1; expires=Mon, 22-Jul-2019 13:38:44 GMT; Max-Age=3600; path=/; domain=dev.myurlthatimhiding.org; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Content-Length: 34
"mysecuretokenstringthatimnotshowing"
How do I get RestSharp to not double encode, or more specifically, to properly handle the double quotes returned?
The response is generated on the PHP side. And as you can see with fiddler, the double quotes are coming from the PHP side and are not inserted by RestSharp.
The content type is the response generated by the PHP service is:
Content-Type: application/json; charset=utf-8
So it's supposed to be JSON.
Usually, JSON data is longer and structured. But it's also valid to return just a string. And in JSON, a string must be enclosed in double quotes.
The back slashes are an artifact of the debugger. I assume you are using Visual Studio. It displays all strings the way the would appear in your source code. In source code you would write:
var t = "\"mysecuretokenstringthatimnotshowing\"";
So the back slashes aren't contained, neither in the response nor in the string. It's just the debugger display.
It's a strange use of JSON. But it's valid. Just remove the double quotes at the beginning and at the end of the string and your fine.
Looks like Execute() gives you content as a string, which would be with the double quotes. To deserialize, you need to provide a type:
var response = request.Execute<string>();
var token = response.Content;
link
I am using gatling for load performance testing on a brand new API. It seems fairly easy and well documented but I am facing an issue as simple as POST a request with Content-Type set to 'application/vnd.api+json' on the Header. All works well when doing the GET stuff but when launching a POST test I get a
HTTP response:
status=
415 Unsupported Media Type
headers=
cache-control: [no-cache]
Content-Type: [application/vnd.api+json; charset=utf-8]
Date: [Fri, 08 Sep 2017 12:57:10 GMT]
Server: [nginx]
Vary: [Origin]
x-content-type-options: [nosniff]
x-frame-options: [SAMEORIGIN]
X-Request-Id: [ff993645-8e01-4689-82a8-2f0920e4f2a9]
x-runtime: [0.040662]
x-xss-protection: [1; mode=block]
Content-Length: [218]
Connection: [keep-alive]
body=
{"errors":[{"title":"Unsupported media type","detail":"All requests that create or update must use the 'application/vnd.api+json' Content-Type. This request specified 'application/json'.","code":"415","status":"415"}]}
Here is the scala code I am using for the http request:
object PostTokenGcm {
val token = exec {
http("TestAPI POST /tokens")
.post("/tokens")
.headers(Map("Authorization" -> testApiToken,
"Content-Type" -> "application/vnd.api+json",
"Accept" -> "application/vnd.api+json" ))
.body(StringBody(gcmTokenRequestBody)).asJSON
.check(status.is(201))
.check(bodyString.exists)
}}
It seems that it is not setting the Content-Type?
Thank you for any lead!
In your POST definition you're using asJSON. According to notes in documentation about request headers:
http("foo").get("bar").asJSON is equivalent to:
http("foo").get("bar")
.header(HttpHeaderNames.ContentType, HttpHeaderValues.ApplicationJson)
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
... so, headers set in:
.headers(Map("Authorization" -> testApiToken,
"Content-Type" -> "application/vnd.api+json",
"Accept" -> "application/vnd.api+json" ))
... get overwritten by asJSON to "application/json" (which is the value of HttpHeaderValues.ApplicationJson).
I'm getting the follow error when I am trying to pipeline a request from Scala spray
[play-akka.actor.default-dispatcher-14] INFO application - Pipelining chain request
[WARN] [03/19/2015 11:08:49.115] [application-akka.actor.default-dispatcher-2] [akka://application/user/IO-HTTP/group-0/0] Illegal response header: Illegal 'Access-Control-Allow-Origin' header: Unexpected end of input, expected $timesAccess$minusControl$minusAllow$minusOrigin (line 1, pos 1):
^
and here is where I am building the request:
val pipeline =
addCredentials(BasicHttpCredentials("API_KEY",
"API_SECRET")) ~> sendReceive
val response: Future[HttpResponse] = pipeline(Post(api,notification))
Logger.info("Pipelining chain request")
response
I don't really know much about Access Control Allow Origin. Do I need to add some sort of header to this request to get it to work?
The error itself means Access-Control-Allow-Origin header wasn't parsed correctly (see grammar). This header is pretty new and allows Cross Origin Resource Sharing. Examples of normal Access-Control-Allow-Origin(from here):
"Access-Control-Allow-Origin" in {
"Access-Control-Allow-Origin: *" =!= `Access-Control-Allow-Origin`(AllOrigins)
"Access-Control-Allow-Origin: null" =!= `Access-Control-Allow-Origin`(SomeOrigins(Nil))
"Access-Control-Allow-Origin: http://spray.io" =!= `Access-Control-Allow-Origin`(SomeOrigins(Seq("http://spray.io")))
}
I can guess that you may use some old version of spray, which doesn't support multiple origins or maybe it's related to this. Anyway, server returns a response with this header only if Origin header is specified in request (which means CORS initiation), so the problem should be solved by removing Origin header from it.
UPDATE: This is a bug of chain.com API, you use. If Origin header is not specified, they return Access-Control-Allow-Origin: (empty string) to you, so it's not parsable:
> curl -v https://api.chain.com/v2/notifications -X POST
> POST /v2/notifications HTTP/1.1
> User-Agent: curl/7.41.0
> Host: api.chain.com
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Methods: GET,POST,PATCH,PUT,DELETE,OPTIONS,HEAD
< Access-Control-Allow-Origin:
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 22 Mar 2015 01:38:07 GMT
< Strict-Transport-Security: max-age=25920000; includeSubDomains
< Vary: Accept-Encoding
< Www-Authenticate: Basic realm="chain-api"
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-Xss-Protection: 1
< Content-Length: 47
< Connection: keep-alive
<
{"code":"CH004","message":"Must authenticate"}
You have to specify some Origin as workaround:
>curl -v https://api.chain.com/v2/notifications -X POST -H "Origin: http://google.com"
> POST /v2/notifications HTTP/1.1
> User-Agent: curl/7.41.0
> Host: api.chain.com
> Accept: */*
> Origin: http://google.com
< HTTP/1.1 401 Unauthorized
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Methods: GET,POST,PATCH,PUT,DELETE,OPTIONS,HEAD
< Access-Control-Allow-Origin: http://google.com
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 22 Mar 2015 01:39:10 GMT
< Strict-Transport-Security: max-age=25920000; includeSubDomains
< Vary: Accept-Encoding
< Www-Authenticate: Basic realm="chain-api"
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-Xss-Protection: 1
< Content-Length: 47
< Connection: keep-alive
I've been trying to use the directory API to add an alias to a group, and it doesn't seems to work, is this feature operational already?
Thank you!
Yes, it works properly. Here's an example of GAM 2.995 creating a domain alias for your reference. I'd need to see code to determine where you're having issues.
$ touch gam/debug.gam
$ gam create alias test-alias#jay.powerposters.org group testme#jay.powerposters.org
Creating alias test-alias#jay.powerposters.org for group testme#jay.powerposters.org
connect: (www.googleapis.com, 443)
send: 'POST /admin/directory/v1/groups/testme#jay.powerposters.org/aliases?alt=json HTTP/1.1
Host: www.googleapis.com
content-length: 44
accept-encoding: gzip, deflate
accept: application/json
user-agent: Google Apps Manager 2.995 / jay#ditoweb.com (Jay Lee)
/ Python 2.7.4 final
/ Linux-3.8.0-26-generic-x86_64-with-Ubuntu-13.04-raring x86_64
/ google-api-python-client/1.1
content-type: application/json
authorization: Bearer ya29.XXX
{"alias": "test-alias#jay.powerposters.org"}'
reply: 'HTTP/1.1 200 OK\r\n'
header: Cache-Control: no-cache, no-store, max-age=0, must-revalidate
header: Pragma: no-cache
header: Expires: Fri, 01 Jan 1990 00:00:00 GMT
header: Date: Wed, 10 Jul 2013 17:34:38 GMT
header: ETag: "2rnFeCLM59Q4Hv06VzEjKQtYAxk/uYyLVNg9ntD0jUUkkana74HyFfQ"
header: Content-Type: application/json; charset=UTF-8
header: Content-Encoding: gzip
header: X-Content-Type-Options: nosniff
header: X-Frame-Options: SAMEORIGIN
header: X-XSS-Protection: 1; mode=block
header: Content-Length: 112
header: Server: GSE
I'm developing an API using close to the latest bits from the aspnetwebstack Codeplex project (4592e2f63c55 from 2012-05-09 if anyone is interested).
I have the following route:
context.Routes.MapHttpRoute("SiteSpecific", "Api/{controller}/{customerId}/{siteToken}/{id}",
new { id = UrlParameter.Optional });
And what I'm currently trying to do is implement get single and a get all in an ApiController. The Get all method, for testing is the following:
public IEnumerable<EditChatResponse> Get(string customerId, string siteToken)
{
return new []{new EditChatResponse{Template = "Get All"}, };
}
And the get single is currently following:
public EditChatResponse Get(string customerId, string siteToken, string id)
{
return new EditChatResponse {Template = "Get Single"};
}
However, routing is always choosing the Get single method:
$ curl -i -H "Accept: applicaiton/json" http://localhost/api/chatresponse/a/b
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 14 May 2012 18:06:26 GMT
Content-Length: 66
{"Id":0,"Template":"Get Single","Inherited":false,"Enabled":false}
$ curl -i -H "Accept: applicaiton/json" http://localhost/api/chatresponse/a/b/c
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 14 May 2012 18:06:28 GMT
Content-Length: 66
{"Id":0,"Template":"Get Single","Inherited":false,"Enabled":false}
I've tried renaming the Get all method to GetAll, as I've seen in some examples, decorating it with [HttpGet], but it still chooses the single method.
Am I completely missing something, or do I need to go about this a different way (most of the examples I see look to be related to the beta bits, and not a recent version from CodePlex)?
Try using this for the default id parameter:
new { id = System.Web.Http.RouteParameter.Optional }