I need to update firmware of my chromecast but I have restriction on my internet and then I cannot update it automatically. I need to update it by pc while I am using vpn. Therefore, I am using following script in powershell. However, the code run successfully but there is no result.
Invoke-WebRequest -Method Post -ContentType "application/json" -Body '{"params": "ota foreground"}' -
Uri "http://<my chrom IP>:8008/setup/reboot" -Verbose -UserAgent "curl"
Here is result of running that script:
VERBOSE: POST http://<my chrom IP>:8008/setup/reboot with -1-byte payload
VERBOSE: received 0-byte response of content type
StatusCode : 200
StatusDescription : OK
Content : {}
RawContent : HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type
Content-Length: 0
Cache-Control: no-cache
Headers : {[Access-Control-Allow-Headers, Content-Type], [Content-Length, 0], [Cache-Control, no-cache]}
RawContentLength : 0
Related
When I'm using the following command:
Invoke-WebRequest -UseBasicParsing -Uri http://example.com -SessionVariable Foo -UserAgent Bar
I get the following output:
StatusCode : 200
StatusDescription : OK
Content : <!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...
RawContent : HTTP/1.1 200 OK
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 1270
Cache-Control: max-age=604800
Content-Type: text/html
Date: Mon, 19 Feb 2018 16:38:28 GMT
Expires: Mon, 26 Feb 2018 16:38...
Forms :
Headers : {[Vary, Accept-Encoding], [X-Cache, HIT], [Content-Length,
1270], [Cache-Control, max-age=604800]...}
Images : {}
InputFields : {}
Links : {#{outerHTML=<a
href="http://www.iana.org/domains/example">More
information...</a>; tagName=A;
href=http://www.iana.org/domains/example}}
ParsedHtml :
RawContentLength : 1270
But the problem is, that I cannot see the headers which were sent (either the session variable or the user agent). Maybe it's get truncated by ...?
How can I display the headers which were sent?
Invoke-WebRequest doesn't store the request header AFAIK. If you want specific values in the header then it expects you to specify them with the parameters -Headers and -UserAgent.
HttpWebRequest or WebRequest provides more control if you prefer that.
$req = [System.Net.HttpWebRequest]::Create("http://www.stackoverflow.com")
$res = $req.GetResponse()
$req.Headers.Keys | % { "$_ = $($req.Headers[$_])" }
Host = stackoverflow.com
$req | fl Method, UserAgent, ProtocolVersion
Method : GET
UserAgent :
ProtocolVersion : 1.1
Command being used:
$Tenant = "tentant_id"
$ClientID = "application_id"
$ClientSecret = "application_password"
$Url = "http://login.microsoftonline.com/$Tenant/oauth2/v2.0/token"
$Body = #{
'client_id' = $ClientID
'scope' = "https://graph.microsoft.com/.default"
'client_secret' = $ClientSecret
'grant_type' = 'client_credentials'
}
Invoke-RestMethod -Method Post -Uri $Url -Body $Body -Verbose
Actual Result:
VERBOSE: POST http://login.microsoftonline.com/<tenant_ID>/oauth2/v2.0/token with -1-byte payload
VERBOSE: received 17293-byte response of content type text/html; charset=utf-8
html
----
html
Expected Result:
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 0,
"access_token": "eyJ0eXAiOiJKV1Q......."
}
Is there something that I'm missing? For some reason when using the above code in Powershell it's returning some sort of webpage, when it should give the token. Using the Chrome extension Postman I was able to construct a POST request using the same url, and client id, scope, client secret and grant type in the body which gives the correct response. Using the access token from that, I can then use the following to get a proper response back:
Invoke-RestMethod -Method Get -Headers #{Authorization = "Bearer $AccessToken"} -Uri https://graph.microsoft.com/v1.0/users/jsmith#example.com
Here's a link to pastebin for the output of $HtmlObject | format-list *
https://pastebin.com/KMMKDGut
As it's too large to format as code here.
Usually, when you get back an HTML response to a JSON or SOAP call, it means that IIS was really upset and is returning back an IIS/ASP.net error page. In that case, you typically need to look at the event logs on the server itself to figure out why IIS/ASP.Net was upset.
Thanks to the suggestion by Marc LaFleur, I took a look at the request with Fiddler. It showed the following:
HTTP/1.1 302 Found
Location: https://login.microsoftonline.com:443/clientID/oauth2/v2.0/token
Server: Microsoft-IIS/8.5
client-request-id: 1d918059-ab39-4d41-8191-b0416d4f03f4
X-Powered-By: ASP.NET
Date: Wed, 10 Jan 2018 21:52:51 GMT
Content-Length: 209
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
Apparently all I had to do was change the original URL to https so that it doesn't have to redirect. Not sure what was happening in the Html object returned though and why I wasn't seeing that in Fiddler.
When calling a URL using
$source = Invoke-WebRequest -Uri $URL
The first request works fine, but in the same session calling a different page from the same domain I get what looks like an encoded source.
Here is a small example
Working URL Call (First Call)
RawContent : HTTP/1.1 200 OK
Content-Language: en-US
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Connection: keep-alive,Transfer-Encoding
Cache-Control: no-store, no-cache
Content-Type: text/html;... Forms : {, filter->form} Headers : {[Content-Language, en-US],
[X-Frame-Options, SAMEORIGIN], [Transfer-Encoding, chunked],
[Connection, keep-alive,Transfer-Encoding]...} Images :
{#{innerHTML=; innerText=; outerHTML=aa846a08e9b3/idm-instruments-pty-ltd-hallam-3803-logo.jpg">;
outerText=; tagName=IMG; title=IDM
Instruments Pty Ltd - logo; class=listing-logo enhanced->logo; alt=IDM Instruments Pty Ltd - logo;
Non Working Call (Second URL Call)
RawContent : HTTP/1.1 200 OK
Content-Language: en-US
X-Frame-Options: SAMEORIGIN
Connection: keep-alive
Content-Length: 14201
Cache-Control: max-age=86400, public
Content-Type: text/html;charset=utf-8
Date:... Forms : {captcha} Headers : >{[Content-Language, en-US], [X-Frame-Options, SAMEORIGIN],
[Connection, keep-alive], [Content-Length, 14201]...} Images
: {#{innerHTML=; innerText=; outerHTML=
alt="Yellow Pages"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAYAAACuwEE+AAAAG
>
XRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAFa5JREFUeNrsXQl4FMXWrYQlLLIJAgYE>BAFZZAeRIKs8FgU1GkBQCPIEcQH9hfwqAoryFEVx+9gVAYOCCgq4REXBCIYlbD4gQESW4BKRhE2IIel
>
3T0/N2Pv0TCaTnpk633cI011d3VV1+9atW7eqo1hkIYZYk/MKYjViJeJl/G8UsaLmmvNEiXiWeI7/zS>H+QczmzIuUCowK47LVIHYhdiReR2xNbFBM9zpC3E38kbiNuJl4kgk4GpWJ8cSFxAyuFUqSGfxZ4vmzC
>
TgAscSHiRuJ+Q4QEjPm82d8mD+zQBBRgZhIXE8sdLCQmLGQP3siL4tAMaEFcQ4xNwSFxIy5vEwtRPMG>Dr2Jn4aRkJjxU15WAT/Rh5gWAYKiZRovu4BNdCZuiEBB0XIDrwsBE9QhJgtB0TGZ140AR2niRIVHVVD
Any Help would be great.
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 do not know much about APIs, but nothing I have seen seems to get me what I need.
This works in the cmd line:
curl -X POST --user user:password --data-raw "Request=GET%2C%2892837F755%29%2C%28" http://url.com
I cannot seem to convert this to anything working in PowerShell. I have tried this, and this, and this, and nothing seems to work.
Anyone got any suggestions?
Thanks to a comment, I tried this:
Invoke-WebRequest -Method Post -UseBasicParsing -Uri "http://example.com/foo?some=param&Request=GET%%2C%%2892837F755%%29%%2C%%28" -Headers #{Authorization=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('username:password'))}
But it returned this:
Invoke-WebRequest :
401 Authorization Required
Authorization Required
This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.
Apache/2.2.3 (Red Hat) Server at rplus.intdata.com Port 80
At line:1 char:1
+ Invoke-WebRequest -Method Post -UseBasicParsing -Uri ""http://example ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
EDIT2:
I figured out how to see the outgoing request from curl, and it looks like this:
C:\windows\system32>curl -X POST --user user:password --data-raw "Request=GET%2C%2892837F755%29%2C%28" http://url.com
* Trying 100.100.100.100...
* TCP_NODELAY set
* Connected to url.com (100.100.100.100) port 80 (#0)
* Server auth using Basic with user 'user'
> POST /url HTTP/1.1
> Host: url.com
> Authorization: Basic *****
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Length: 87
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 87 out of 87 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script results follow
< Content-type: text/plain
<
"theResponseIExpected"
* Curl_http_done: called premature == 0
* Closing connection 0
(I changed a bunch of the actual strings in the text above...).
SO, it looks like there's this basic authentication in the header, followed by some 20-digit alphanumeric thing (***** in the text above). What is that? How does curl generate that? If it is some sort of encryption or translation, it looks as if it is only changing the password, and not the user. Not sure if that is the same as what this does - ToBase64String([Text.Encoding]::ASCII.GetBytes('user:password'))
Edit 3:
This seems to work, and seems to get a response, but PowerShell doesnt seem to like it:
$user = "user"
$pass = "password"
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = #{ Authorization = $basicAuthValue }
Invoke-WebRequest -Uri "url.com?Request=..." -Headers $headers
I am now getting the following:
Invoke-WebRequest : The server committed a protocol violation. Section=ResponseStatusLine
At line:13 char:1
I have found a few posts related to this, but they all want me to change a config file. I have tried that, but it does not seem to work. It seems the response is in HTTP1.0, and InvokeWebRequest wants 1.1. Is there a way within this script to let it allow 1.0 responses??