How to post data to specific URL using WebClient in C#
I just found the solution and yea it was easier than I thought :)
so here is the solution:
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
it works like charm :)
Set a body for WebClient when making a Post Request
You can do with this simple code
Uri uri = new Uri("yourUri");
string data = "yourData";
WebClient client = new WebClient();
var result = client.UploadString(uri, data);
Remember that you can use UploadStringTaskAsync if you want to be async
Post Data To A Specific URL & Shows The Return Page
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
string orderNo = postProcessPaymentRequest.Order.Id.ToString();
string amount = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);
string merchantId = _NetConnectPaymentSettings.CustomerId;
string date = DateTime.Now.ToString("dd/MM/yyyy");
string time = DateTime.Now.ToString("HH:mm:ss");
string urlNetConnect = _NetConnectPaymentSettings.PaymentPage;
string checksum = Generate_MerchantRequest_Check_Sum("7C12B6AECC51A3F3189799098AB1981", merchantId, orderNo, amount, date, time);
var client = new HttpClient();
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Merchant_ID", merchantId));
values.Add(new KeyValuePair<string, string>("Order_NO", orderNo));
values.Add(new KeyValuePair<string, string>("Order_Amount", amount));
values.Add(new KeyValuePair<string, string>("Date", date));
values.Add(new KeyValuePair<string, string>("Time", time));
values.Add(new KeyValuePair<string, string>("CheckSum", checksum));
values.Add(new KeyValuePair<string, string>("Transaction_Desc", "Shop From SM Motors"));
var content = new FormUrlEncodedContent(values);
//HttpResponseMessage response = client.PostAsync("http://www.smmotors.org", content).Result;
HttpResponseMessage response = client.PostAsync(urlNetConnect, content).Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync();
HttpContext.Current.Response.Write(responseString.Result);
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.End();
_webHelper.IsPostBeingDone = true;
}
else
{
throw new NopException();
}
return;
}
how to convert my Webclient to send Post request instead of Get request
Use UploadStringTaskAsync instead of DownloadStringTaskAsync
.
var url = currentURL+ "home/scanserver";
wc.Headers.Add("Authorization", token);
var json =wc.UploadStringTaskAsync(url, "FQDN=allscan");
NOTE that json
is a Task<string>
not a string
. Are you sure that you want to use async behaviour?
How to post parameter to Azure Service URL using WebClient in C#
You'll be better off using HttpClient
instead of WebClient
. By looking at what the C++ code does it should be something like this in C# using HttpClient
public void Test() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = client.PostAsync("api/test?value=1234", new StringContent(string.Empty)).Result;
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = response.Content.ReadAsStringAsync().Result;
var responseContentAsBYtes = response.Content.ReadAsByteArrayAsync().Result;
}
}
Here is the async version of the code above
public async Task TestAsync() {
using (HttpClient client = new HttpClient()) {
client.BaseAddress = new Uri("http://testservice.cloudapp.net");
var response = await client.PostAsync("api/test?value=1234", new StringContent(string.Empty));
var statusCode = response.StatusCode;
var errorText = response.ReasonPhrase;
// response.EnsureSuccessStatusCode(); will throw an exception if status code does not indicate success
var responseContentAsString = await response.Content.ReadAsStringAsync();
var responseContentAsBYtes = await response.Content.ReadAsByteArrayAsync();
}
}
POSTing JSON to URL via WebClient in C#
You need a json serializer to parse your content, probably you already have it,
for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,
POST request using C# WebClient
As per the documentation (https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstring?view=net-5.0), UploadString sends a POST request by default.
So if you replace all your references to $_GET
with $_POST
in the PHP it should find the variables.
Alternatively you can specify the HTTP method when you call UploadString, e.g.
wc.UploadString(URI, "GET", myParameters)
Specific documentation for that method overload: https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstring?view=net-5.0#System_Net_WebClient_UploadString_System_String_System_String_System_String_
P.S. your code is vulnerable to SQL injection attacks. You're using prepared statements, but that provides no protection unless you also use parameters with them. See How can I prevent SQL injection in PHP? for examples of how to create your queries safely in PHP.
Receive data from server using POST method and with a request body using WebClient in C#
Big Thanks to @Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json");
in the request header. Changing it to wc.Headers.Add("Content-Type: application/json");
returned a 200 Ok response. The code modification is as follows
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept
tells the server the kind of response the client will accept and Content-type
is about the payload/content of the current request or response. Do not use Content-type
if the request doesn't have a payload/ body.
More information about this can be found here.
Related Topics
Split a String by Another String in C#
How to Retrieve Id of Inserted Entity Using Entity Framework
Linq to Entities Case Sensitive Comparison
How to Extract Text That Lies Between Parentheses (Round Brackets)
Deserializing Json Data to C# Using Json.Net
Color Different Parts of a Richtextbox String
How to Rethrow an Exception in C#
Running Multiple Async Tasks and Waiting For Them All to Complete
How to Easily Check If Access Is Denied For a File in .Net