How do I send a raw POST request in Visual Basic - vb.net

How would I send a raw POST request in Visual Basic .NET (2010)? When I say raw, I mean without using System.Net.WebRequest to form one, but rather by forming your own headers and sending them with the StreamWriter..
I think I know how to do it with a GET request, but I'm not sure how I would send a POST request.
...
Example GET request (NOTE THAT HERE I USE WEBREQUEST, WHICH I DON'T WANT TO):
Private Function HTTPGet(ByVal URL As String) As String
On Error GoTo fail
Dim Output As String = String.Empty
Dim Request As WebRequest = WebRequest.Create(URL)
Request.Method = "GET"
Using Response As WebResponse = Request.GetResponse
Using Stream As Stream = Response.GetResponseStream
Output = (New StreamReader(Stream)).ReadToEnd
End Using
End Using
Return Output
fail:
Return Nothing
End Function

If you really want to manually create these POST's, you will have to do a little research on HTTP requests and sockets. Sockets will create connections to a destination service and let you determine what data you want to send. To build the data properly, you will need to research what the format will need to be for an HTTP POST.
Check out this link to learn more about HTTP GET/POST. Scroll down to (The POST Method) to see a sample HTTP POST.
http://www.jmarshall.com/easy/http/
Here is a link on sockets:
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx

Related

Format this GET request in VB.NET code behind?

I am trying a "GET" method to request a count of activities from the Accelo API here:
https://api.accelo.com/docs/?http#count-activities
And although i've used a very similar POST method to successfully get the access token using an authentication method, I cannot for the life of me figure out how to get the count of activities. The API says to use "GET" and past the access token as "bearer..." and I've also tried doing a post and getting the stream first, tried sending in some data and accessing the "list activities" endpoint instead...nothing is working. everything I do returns the error "400. Bad Request."
I've tried passing data in a query string format directly in the URI, and tried passing no data since its a GET function. It looks to me like I'm following the API exactly.
Dim data2 = Nothing ' Encoding.UTF8.GetBytes(jsonstring)
Dim _list = GetListOfActivities(New Uri("https://example.api.accelo.com/api/v0/activities/count.xml"), data2, _AccessToken)
Dim reqa As WebRequest = WebRequest.Create(uri)
' reqa.Method = "GET"
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
reqa.Headers.Add("Authorization", "Bearer " & _AccessToken)
reqa.ContentType = "application/x-www-form-urlencoded"
'reqa.ContentLength = jsonDataBytes.Length
' Dim streama = reqa.GetRequestStream()
' streama.Write(jsonDataBytes, 0, jsonDataBytes.Length)
'streama.Close()
Dim responsea As WebResponse = reqa.GetResponse()
Console.WriteLine((CType(responsea, HttpWebResponse)).StatusDescription)
I must be formatting the request wrong - please help?
My problem turned out to be something stupid, and literally beyond the scope of what I posted here. I had specified a "scope" in my initial request to get the access token that was set to read-only "staff" data (I had copied-and-pasted their example online into my code, for other parameters like grant type, and I brought the scope along with it), and in this scenario here I was trying to access "activities" data and not "staff" data. I would have thought I'd get a permissions-related error, instead of "bad request" which confused me, but anyway it works now.
The above code - actually with this line:
reqa.Method = "GET"
instead of this line:
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
Works just fine since I changed my scope to read(all) in my initial web method getting the access token.

Client POST of indeterminate length to a server

[Java DSL] I'm trying to post a stream of bytes to a server (as the body) using the client api in real-time but won't know the length prior to the start of the request.
I can't figure out how to do this from the akka-http documentation, has anyone attempted this?
Given that, you have created a materializer from the Akka context and have a Source that generates ByteString objects called mysource:
Http httpContext =
Http.get(context().system());
Source<ByteString, NotUsed> chunked =
mysource.map(str -> ByteString(str.concat("\n")))
.concat(Source.single(ByteString.empty()));
HttpRequest post = HttpRequest.POST("http://some-server/address")
.withEntity(HttpEntities.createChunked(ContentTypes.APPLICATION_OCTET_STREAM, chunked))
.withProtocol(HttpProtoclas.HTTP_1_1);
CompletionStage<HttpResponse> result =
httpContext.singleRequest(post, materializer);
Note that we concatenate an empty ByteString Source object to the original Source in order to signal the end of the chunked stream.
If you are issuing this from within an actor it's best to use a pipe() to submit the final request.

VBA http get request response is gibberish

I tried to search for a quick answer to this but I did not see a response...so I apologize if this is redundant.
I am pretty new to VBA and only use it to pull data from APIs to make my life easier.
My question is about the response im getting from a particular API. HEre is the code im using:
Dim URL As String: URL = "API URL HERE in json format"
Dim Http As New WinHttpRequest
Dim Resp As String
Http.Open "GET", URL, False
Http.Send
Resp = Http.ResponseText
Debug.Print Resp
So the Resp text is complete gibberish...is this a security thing? I pass a security key successfully when I use it in the browser so I assumed it was not that.... I have used this exact method on numerous APIs but this is the first time I have seen this garbled response. FYI the url I am using works just fine in a browser.
The Resp looks like this for example:
gõi:?ñq¢²^2?7AÄ??æºz³Gs=ΠÜ?¬«¤%?$ÖÉ'q¯¼|?¼²ôue¦½Þ"HË!ø5[4]s½?·Þ.OÛÃBh×?4"rÊÊ[r7
Thanks for any help!
Khauna

What Sanitizes Data From REST/Web APIs?

I have a REST Service built in vb.net running on IIS. I've noticed that the returned data is sanitized or escaped, e.g.:
<script>alert('testing1')</script>
is returned as:
<script>alert('testing1')</script>
Can anyone tell me what is doing the escaping, would it be .net or IIS and can it be switched on or off?
I'm pretty sure you could have a controller method like this..
Function ReturnJavascript() As Net.Http.HttpResponseMessage
Dim resp As New Net.Http.HttpResponseMessage(Net.HttpStatusCode.OK)
resp.Content = New Net.Http.StringContent("<script>alert('testing1')</script>", System.Text.Encoding.UTF8, "text/plain")
Return resp
End Function
Not sure what you are trying to accomplish. If you don't want to return as a response message, you might attempt returning as content set to text/plain.

Append URL Query Strings to request

I'm trying to send a POST request and format the query string in a specific format. Order doesn't matter aside from the first parameter, but I haven't been successful.
What I need:
localhost/someapp/api/dosomething/5335?save=false&userid=66462
What some of my attempts have spit out:
http://localhost/someapp/api/dosomething/?Id=29455&save=false&userId=797979
http://localhost/someapp/api/dosomething/?save=false&userId=797979
How I formatted the request:
request.AddQueryParameter("Id", "29455");
request.AddQueryParameter("save", "false");
request.AddQueryParameter("user", "4563533245");
If I try AddParameterfor Id it doesn't get appended on the query string (I'm thinking because it's a POST and not a GET), so that won't work. The API isn't expecting a form, it's expecting :
(string id, List<Dictionary<string,string>>)
I could use a StringBuilder, but that feels wrong. I'm not sure if UrlSegment is the best way to go either, since I would basically be hacking the query string. Is there a way to format my request in the format I need using RestSharp's API?
What I ended up using is UrlSegment and then kept the .AddQueryParameter methods, so the final code block looks like :
var url = new RestClient(localhost/someapp/api/dosomething/{id});
var request = new RestRequest(Method.POST);
request.AddParameter("Id", "5335", ParameterType.UrlSegment);
request.AddQueryParameter("save", "true");
request.AddQueryParameter("UserId", "5355234");
Which produced the URI I needed.
The easiest coding process for using RestSharp or any other API client library would be to use Postman to generate if you are unsure of how to code it. Download Postman, do a new request, enter the URL string to send to the API, click on Code, select C# (RestSharp) from the dropdown. Here is the code it generated.
var client = new RestClient("http://localhost/someapp/api/dosomething /5335?save=false&userid=66462");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "bd05aa45-f1b9-4665-a3e7-888ad16f2800");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);