我如何能使一个HTTP POST请求和发送数据的主体?
当前回答
还有另一种做法:
using (HttpClient httpClient = new HttpClient())
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new StringContent(param1), "param1");
form.Add(new StringContent(param2), "param2");
using (HttpResponseMessage response = await httpClient.PostAsync(url, form))
{
response.EnsureSuccessStatusCode();
string res = await response.Content.ReadAsStringAsync();
return res;
}
}
通过这种方式,您可以轻松地发布一个流。
其他回答
这是一个完整的JSON格式发送/接收数据的工作示例,我使用Visual Studio 2013 Express Edition:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
class Customer
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
public class Program
{
private static readonly HttpClient _Client = new HttpClient();
private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();
static void Main(string[] args)
{
Run().Wait();
}
static async Task Run()
{
string url = "http://www.example.com/api/Customer";
Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
var json = _Serializer.Serialize(cust);
var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
string responseText = await response.Content.ReadAsStringAsync();
List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);
Console.WriteLine(responseText);
Console.ReadLine();
}
/// <summary>
/// Makes an async HTTP Request
/// </summary>
/// <param name="pMethod">Those methods you know: GET, POST, HEAD, etc...</param>
/// <param name="pUrl">Very predictable...</param>
/// <param name="pJsonContent">String data to POST on the server</param>
/// <param name="pHeaders">If you use some kind of Authorization you should use this</param>
/// <returns></returns>
static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = pMethod;
httpRequestMessage.RequestUri = new Uri(pUrl);
foreach (var head in pHeaders)
{
httpRequestMessage.Headers.Add(head.Key, head.Value);
}
switch (pMethod.Method)
{
case "POST":
HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
httpRequestMessage.Content = httpContent;
break;
}
return await _Client.SendAsync(httpRequestMessage);
}
}
}
如果需要POST JSON消息体,可以使用以下方法。假设您有一个名为m的类实例。
string jsonMessage = JsonConvert.SerializeObject(m);
// Make POST call
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "<url here>");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// Do something here
}
}
到目前为止,我找到了简单的解决方案(一行程序,没有错误检查,没有等待响应):
(new WebClient()).UploadStringAsync(new Uri(Address), dataString);
请谨慎使用!
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");
简单的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);
}
推荐文章
- 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循环中编辑字典值