How to post data with C# in mono? - c#

1)
WebRequest request = WebRequest.Create("");
I can not use this method.
The reason is my mono can not load the System.Net.Configuration.WebRequsetModulesSection.
2)
Navigate(bstrURL, &vFlags, &vTargetFrameName, &vPostData, &vHeaders);
I can not use this method.
The reason is can not use the namespace using System.Windows.Forms;
What else can I use to post data to the URL.

You can use HttpClient:
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[0]);
var response = await httpClient.PostAsync("URL", content);
string responseAsString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseAsString);

Related

POST request in NET Core (C#) from python to C#

import requests
requests.post('https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start',
auth=('john#doe.com', 'secretPassword'))
How would one write this in C#? (NET Core)
Apart of the added comments, I would recommend using a library called RestSharp.
You can easily find the nuget package and the code will be as easier as:
var client = new RestClient("https://dathost.net");
client.Authenticator = new HttpBasicAuthenticator("john#doe.com", "secretPassword");
var request = new RestRequest("api/0.1/game-servers/{id}/start", Method.POST);
request.AddUrlSegment("id", "54f55784ced9b10646653aa9");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
You can also do async requests:
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
You can do it with HttpClient.
Add usings top of your code first.
using System.Net.Http;
using System.Net.Http.Headers;
And run this code wherever you want.
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("john#doe.com:secretPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await client.PostAsync(
"https://dathost.net/api/0.1/game-servers/54f55784ced9b10646653aa9/start", null);
Hope this helps.

How to serialize-deserialize object using HTTP GetAsync method?

After I upgraded the framework of web app from 4.0 to 4.6 I found that there is no more ReadAsAsync() method in HTTP protocol library, instead of ReadAsAsync() there is GetAsync(). I need to serialize my custom object using GetAsync().
The code using ReadAsAsync():
CustomResponse customResponse = client.ReadAsAsync("api/xxx", new StringContent(new JavaScriptSerializer().Serialize(request), Encoding.UTF8, "application/json")).Result;
Another example based on ReadAsAsync()
CustomResponse customResponse = await Response.Content.ReadAsAsync<CustomResponse>();
How to achieve same goal using GetAsync() method ?
You can use it this way:
(you might want to run it on another thread to avoid waiting for response)
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(page))
{
using (HttpContent content = response.Content)
{
string contentString = await content.ReadAsStringAsync();
var myParsedObject = (MyObject)(new JavaScriptSerializer()).Deserialize(contentString ,typeof(MyObject));
}
}
}

SOAP Request with HttpClient

I'am trying to reach a SOAP API using the HttpClient object. I've searched everywhere but most of the people are using the HttpWebRequest object which is not supported by the DNX Core framework.
Does anyone have a working example of a SOAP request using the HttpClient object?
This image represents a simple request from this API (NuSOAP PHP):
Thank you!
EDIT :
So I was able to call the API with the following code:
Uri uri = new Uri("http://localhost/teek_api/service.php");
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Add("SOAPAction", "http://localhost/teek_api/service.php/ping");
var content = new StringContent("text/xml; charset=utf-8");
using (HttpResponseMessage response = await hc.PostAsync(uri, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
string value = await response.Content.ReadAsStringAsync();
return value;
}

Send and receive a post variable

I'm trying to send a post variable to the url which I'm redirecting to.
I'm currently using the Get method and sending it like this:
// Redirect to page with url parameter (GET)
Response.Redirect("web pages/livestream.aspx?address="+ ((Hardwarerecorders.Device)devices[arrayIndex]).streamAddress);
And retrieving it like this:
// Get the url parameter here
string address = Request.QueryString["address"];
How do I convert my code to use the POST method?
B.T.W., I don't want to use a form to send the post variable.
Using HttpClient:
To send POST query:
using System.Net.Http;
public string sendPostRequest(string URI, dynamic content)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://yourBaseAddress");
var valuesAsJson = JsonConvert.SerializeObject(content);
HttpContent contentPost = new StringContent(valuesAsJson, Encoding.UTF8, "application/json");
var result = client.PostAsync(URI, contentPost).Result;
return result.Content.ReadAsStringAsync().Result;
}
Where 'client.PostAsync(URI, contentPost)' is where the content is being sent to the other website.
On the other website, an API Controller needs to be established to receive the result, something like this:
[HttpPost]
[Route("yourURI")]
public void receivePost([FromBody]dynamic myObject)
{
//..
}
However, you might also want to look into using a 307 re-direct, especially if this is a temporary solution.
https://softwareengineering.stackexchange.com/a/99966
using System.Net.Http;
POST
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
GET
using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}
My Personal Choice is Restsharp it's fast but for basic operations you can use this

HttpClient with chunk data not working

When I execute the query in Firefox/IE I get the full response; but when I execute the same request with HttpClient I get only a part. I don't understand why.
Apparently the data are chunked that's why I specify the ResponseContentRead.
var requestUri = "https://api.guildwars2.com/v2/continents/1/floors/1";
HttpClient httpClient = new HttpClient();
var request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = requestUri;
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
var result = await response.Content.ReadAsStringAsync();
Why Firefox/IE returns the right response and HttpClient an incomplete one ?
Result from HttpClient:
Result from Firefox/IE:
The code is inside a C# UWP app.
I have successfully ran your code and gotten the entire json string. However, I had to make a minor modification in order to get it working:
var requestUri = new Uri("https://api.guildwars2.com/v2/continents/1/floors/1");
HttpClient httpClient = new HttpClient();
var request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = requestUri;
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
var result = await response.Content.ReadAsStringAsync();
Note the requestUri being initialized as an Uri instance instead of a string instance.
Also, the code has been tested in a console application.
EDIT: Here is a paste of what I got from the call. I've beautified the code to make it more readable. Perhaps it helps you validate if the content is as expected: Json result

Categories