我如何能使一个HTTP POST请求和发送数据的主体?
当前回答
在. net Core中,你可以用下面的代码进行POST调用。在这里,我为这段代码添加了一些额外的特性,这样您就可以让您的代码在代理后工作,如果有网络凭据的话。
在这里我还提到,您可以更改消息的编码。
HttpClient client = GetHttpClient(_config);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
}
client.BaseAddress = new Uri(baseAddress);
Encoding encoding = Encoding.UTF8;
var result = await client.PostAsync(url, new StringContent(body, encoding, "application/json")).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
return new RequestResponse { severity = "Success", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}
else
{
return new RequestResponse { severity = "failure", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}
public HttpClient GetHttpClient(IConfiguration _config)
{
bool ProxyEnable = Convert.ToBoolean(_config["GlobalSettings:ProxyEnable"]);
HttpClient client = null;
if (!ProxyEnable)
{
client = new HttpClient();
}
else
{
string ProxyURL = _config["GlobalSettings:ProxyURL"];
string ProxyUserName = _config["GlobalSettings:ProxyUserName"];
string ProxyPassword = _config["GlobalSettings:ProxyPassword"];
string[] ExceptionURL = _config["GlobalSettings:ExceptionURL"].Split(';');
bool BypassProxyOnLocal = Convert.ToBoolean(_config["GlobalSettings:BypassProxyOnLocal"]);
bool UseDefaultCredentials = Convert.ToBoolean(_config["GlobalSettings:UseDefaultCredentials"]);
WebProxy proxy = new WebProxy
{
Address = new Uri(ProxyURL),
BypassProxyOnLocal = BypassProxyOnLocal,
UseDefaultCredentials = UseDefaultCredentials,
BypassList = ExceptionURL,
Credentials = new NetworkCredential(ProxyUserName, ProxyPassword)
};
HttpClientHandler handler = new HttpClientHandler { Proxy = proxy };
client = new HttpClient(handler, true);
}
return client;
}
其他回答
当使用Windows.Web.Http命名空间时,对于POST而不是FormUrlEncodedContent,我们编写HttpFormUrlEncodedContent。同样,响应类型为HttpResponseMessage。其余的就像Evan Mulawski写的那样。
到目前为止,我找到了简单的解决方案(一行程序,没有错误检查,没有等待响应):
(new WebClient()).UploadStringAsync(new Uri(Address), dataString);
请谨慎使用!
这是一个HTTPS web请求的例子。可以在PHP脚本中回显任何结果。最后,PHP回显字符串将在c#客户端显示为警报。
string url = "https://mydomain.ir/test1.php";
StringBuilder postData = new StringBuilder();
postData.Append(String.Format("{0}={1}&", HttpUtility.HtmlEncode("username"), HttpUtility.HtmlEncode("ali")));
postData.Append(String.Format("{0}={1}", HttpUtility.HtmlEncode("password"), HttpUtility.HtmlEncode("123456789")));
StringContent myStringContent = new StringContent(postData.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpClient client = new HttpClient();
HttpResponseMessage message = client.PostAsync(url, myStringContent).GetAwaiter().GetResult();
string responseContent = message.Content.ReadAsStringAsync().GetAwaiter().GetResult();
DisplayAlert("Your Feedback", responseContent, "OK");
PHP服务器端:
<?php
if (isset($_POST["username"]) && $_POST["username"] == "ali") {
echo "Yes, hi Ali";
}
else {
echo "No, where is Ali?";
}
?>
结果将是“Yes, hi Ali”。
这是为Xamarin形式。对于一个c# .NET应用程序,将DisplayAlert替换为:
MessageBox.show(responseContent);
简单的GET请求
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
简单的POST请求
using System.Net;
using System.Collections.Specialized;
...
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
}
c# . net
using System.Net.Http;
private static readonly HttpClient httpClient = new HttpClient();
//POST
var values = new Object();
values[0] = "Value1";
values[2] = "Value2";
values[n] = "ValueN";
var content = new FormUrlEncodedContent(values);
var response = await httpClient.PostAsync("URL", content);
var responseString = await response.Content.ReadAsStringAsync();
//GET
var response = await httpClient.GetStringAsync("URL");
推荐文章
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- 我如何捕捉Ajax查询后错误?
- AutoMapper:“忽略剩下的?”
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接
- 如何使用。net 4运行时运行PowerShell ?
- 在foreach循环中编辑字典值