Dim myUri = New Uri("https://squareup.com/v2/locations")
Dim RQ As HttpWebRequest = TryCast(WebRequest.Create(myUri), HttpWebRequest)
RQ.PreAuthenticate = True
RQ.Headers.Add("Authorization", "Bearer" & Token) '''Token is a Shared string assigned to my current Access Token
RQ.Method = "GET"
RQ.Accept = "application/json"
RQ.ContentType = "application/json"
Using response As HttpWebResponse = TryCast(RQ.GetResponse(), HttpWebResponse) '''''"The remote server returned an error: (404) Not Found."
Very new to the Square-Connect API and there are no vb.net examples so this was as far as i can get. Im not able to get pass the last line. I always get a 404 error no matter what i try. Anyone know why.
If I use this command (replacing Token with my access Token), in a terminal then I get the result I want in vb.net.
curl -H "Authorization: Bearer Token" https://connect.squareup.com/v2/locations
The guys at square quickly found my problem so here is the working code:
Dim myUri = New Uri("https://connect.squareup.com/v2/locations")
Dim RQ As HttpWebRequest = TryCast(WebRequest.Create(myUri), HttpWebRequest)
RQ.PreAuthenticate = True
RQ.Headers.Add("Authorization", "Bearer " + Token) 'Token is a Shared string assigned to my current Access Token
RQ.Method = "GET"
RQ.Accept = "application/json"
RQ.ContentType = "application/json"
Using response As HttpWebResponse = TryCast(RQ.GetResponse(), HttpWebResponse)
Related
I want to do this (works):
curl --request POST "http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns" --header "Authorization: Token 12345..." --header "Content-Type: text/plain; charset=utf-8" --header "Accept: application/json" --data-binary "solar,mytag=1 cwatt=125"
in vb.net without using influx library. I tried this:
Dim httpClient As HttpClient = New HttpClient()
Dim DAhttpContent As StringContent = New StringContent("solar,mytag=1 cwatt=222", Encoding.UTF8, "text/plain")
DAhttpContent.Headers.Add("Authorization:", "Token 12345...")
DAhttpContent.Headers.Add("Content-Type:", "text/plain; charset=utf-8")
DAhttpContent.Headers.Add("Accept:", "application/json")
Dim response = httpClient.PostAsync("http://192.168.1.99:8086/write?db=data&u=user1&p=writewrite1", DAhttpContent)
Error-> System.FormatException: "The header name format is invalid."
So I read many topics here on overflow and tried something else:
Private Shared Async Function Main3() As Task
Using xclient As HttpClient = New HttpClient()
Dim request_json = "solar,mytag=1 cwatt=222"
Dim content = New StringContent(request_json, Encoding.UTF8, "text/plain")
Dim authenticationBytes = Encoding.ASCII.GetBytes("12345...")
xclient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", Convert.ToBase64String(authenticationBytes))
xclient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim result = Await xclient.PostAsync("http://192.168.1.99:8086/api/v2/write?org=db1&bucket=data&precision=ns", content)
'Dim result_string As Task(Of String) = result.Content.ReadAsStringAsync() '<- Error "Content is no Member of Task(Of HttpResponseMessage)"
End Using
End Function
It runs without any error but also does not writes any data. So my problems are:
how to authenticate in Header correctly?
wait/return response outside Async function
Maybe it's easier to do by UDP (8089) packet transmission?
Any vb.net code example would be very helpful for me.
(I also cheked many similar questions here before.)
Thanks in advance!
I've made an experimental email and password system using post requests to my Wix site API and I've verified it works through curl and postman. When trying to use it in my VB.NET app however I get the error: "The underlying connection was closed: An unexpected error occurred on a receive." I already previously ran into a "Could not create SSL/TLS secure channel" error but that was resolved when I moved the .NET framework for the project to 4.7.1 and made sure SecurityProtocol was set to SystemDefault as Wix seems to use TLS 1.3. Now however I'm getting this error on receive that I have no idea how to resolve as everything in the request seems to look ok:
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(New Uri("https://xxxxx.com/mysite/_functions/check?email=" & email & "&pass=" & LCase(passHash))), HttpWebRequest)
req.Method = "POST"
req.ContentType = "none"
req.ContentLength = 0
req.Host = "test"
req.KeepAlive = True
Dim result As HttpWebResponse = req.GetResponse()
The error is thrown when running 'req.GetReponse()'.
After looking at countless versions of sample code for .NET POST requests and questions about this error but everyone seems to suggest setting the security prococol type, which I have done and setting it as the system default is the only way I don't get an internal server error status. Another was setting KeepAlive to false, which I have also tried but didn't make any difference.
What could be the problem here? Here is what's included in the postman header if this is of help:
Ok so eventually I ended up changing my code to use GetResponseAsync() instead of GetResponse() (not that it made any difference to the problem) and set the protocol type back to Tls12 on .NET 4.8. In the end it seemed that having req.Host set was what was causing the issue with the response, Wix doesn't seem to like it. I also added some extra settings to the request but ultimately they make no difference to the response. Here is the final working code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim req As HttpWebRequest = WebRequest.CreateHttp("https://example.com/check?email=" & email & "&pass=" & LCase(passHash))
req.Method = "POST"
req.ContentType = "none"
req.ContentLength = 0
req.KeepAlive = True
req.CookieContainer = New CookieContainer()
req.UserAgent = "Test"
req.Accept = "ext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.9,en;q=0.5")
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8")
req.Headers.Add(HttpRequestHeader.CacheControl, "no-cache")
Dim statusCode As HttpStatusCode = Nothing
Try
Using result As HttpWebResponse = CType(Await req.GetResponseAsync(), HttpWebResponse)
statusCode = result.StatusCode
End Using
If statusCode = HttpStatusCode.OK Then
MsgBox("Valid")
Else
Dim response As String = New StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd()
MsgBox(response)
End If
Catch webEx As WebException
MsgBox(New StreamReader(webEx.Response.GetResponseStream()).ReadToEnd())
End Try
Trying to implement var client = new RestClient("https://bim360field.autodesk.com/fieldapi/checklists/v1/06eede44-a707-4f0b-9529-78abea6e6bf5");
var request = new RestRequest(Method.GET); https://bim360field.autodesk.com/apidoc/index.html#fieldapi/checklists/v1/checklists_api_method_2 in my C# solution.
I've set up an example Get Request in Postman. Works perfectly with the form-data, x-www-form-urlencoded, no auth, bearer token.
Tried to copy the exact Restshap Request code from Postman to my C# app. Does not work; always responds with "Unauthorized". Tried changing cookie mngmt, and auth window/nltm mngmt. Did not help.
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "91");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Cookie", "OPTOUTMULTI_REF=b7027893-8564-4b33-8f1e-de0c175d38c6; OPTOUTMULTI_GEO=NL; utag_main=v_id:016639c85215001e1ab9f566c61201090006808800bd0$_sn:4$_ss:0$_st:1545042741235$ses_id:1545040922510%3Bexp-session$_pn:1%3Bexp-session; XSRF-TOKEN=YxM2BdzM19rML7OjKGZqcD0hAqv%2F225McEm8oB3m7No%3D; 75da74d446a8376e2cf6a286ff63573ab705f04c36540fdda21c1dbc1928d4e72cabf30a63e339690e88fc3801a93e44e6e3ddc20651f602d2c5eaaf49b21d61=f795a05c211085d994bf2e08996ff747");
request.AddHeader("Host", "bim360field.autodesk.com");
request.AddHeader("Postman-Token", "0b3c652d-462c-4aba-a661-476309792018,b4d4846c-a928-406f-837c-f16809a9bccd");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.15.2");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"ticket\"\r\n\r\n{API_TICKET}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"project_id\"\r\n\r\n049bf984-b8d1-4330-a17c-0832c6facf49\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);```
I expect that this code is also working with Restsharp. Do I miss anything?
For your cookies you will need to setup a CookieContainer on your Client.
Client = new RestClient(Request.GetEnvironment())
{
CookieContainer = new System.Net.CookieContainer()
};
You don't need the Postman Token. You will want to use the Bearer Token provided by your API to make the call and add it to your headers or parameters.
When intializing RestClient you only want to pass the base url. Then pass the rest of your api path during the RestRequest initialization. This will help for future use when wanting to hit more than one end point with the same cookies.
Here is a working example for you:
// (1) Build request
var client = new RestClient();
client.BaseUrl = new System.Uri("https://bim360field.autodesk.com/");
// Set resource or end point
var request = new RestRequest();
request.Resource = "/fieldapi/checklists/v1";
request.Method = Method.GET;
// Add parameters
request.AddParameter("ticket", "{API_TICKET}");
request.AddParameter("project_id", "049bf984-b8d1-4330-a17c-0832c6facf49");
// (2) Execute request and get response
IRestResponse response = client.Execute(request);
Hope it helps!
I am trying to hit a rest API using HttpWebRequest and I have to authenticate Proxy Server before I can hit a Rest API.
For authorizing proxy Server, I am adding credentials to HttpWebrequest.Proxy.credentials.
Now, my scenario is that, I am accessing the Rest API twice, first with Correct Proxy Credentials and then with wrong Proxy credentials.
With Correct Proxy Credentials I getthe out put as expected but with wrong credentials I am again able to fetch data from rest API.
If I reverse the order of APIs that is with wrong credentials first and then ith right creentials then I get 407 erro on 1st API hit which is correct.
How is this possible.
Here is my Code :
1st Call :
Dim myHttpWebRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)
myHttpWebRequest.Headers.Add("Proxy-Authorization", "Basic dXNlcjE6UGFzc3dvcmQx")
myHttpWebRequest.Method = "GET"
myHttpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None
Dim myHttpWebResponse = GetresponseForRequest(myHttpWebRequest)
2nd Call
Dim myHttpWebRequest1 As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)
myHttpWebRequest1.Headers.Add("Proxy-Authorization", "Basic dXNlcjE8UKFzc3dvcmQn")
myHttpWebRequest1.Method = "GET"
myHttpWebRequest1.AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None
Dim myHttpWebResponse1 = GetresponseForRequest(myHttpWebRequest)
When attempting to add a value to the header of an HTTP request, I get the following error:
Specified value does not have a ':' separator. Parameter name: header
To add the header I am using the following code:
Dim request As HttpWebRequest = WebRequest.Create(url)
Dim soapXML As New XmlDocument()
soapXML.LoadXml(soapEnvelope)
request.Headers.Add("SOAPAction", action)
request.Method = "POST"
request.ContentType = "text/xml;charset=""utf-8"""
request.Accept = "text/xml"
Using stream As Stream = request.GetRequestStream()
soapXML.Save(stream)
End Using
I have been looking all over the place and haven't found anybody who has had any similar errors, outside of this SO question: using httpRequest headers?
Which didn't help much.
Does anybody know what I might be doing wrong here?
EDIT 1: Added all the code that I currently have that creates my web request.