C#怎么使用HttpClient来Post数据
推荐于2016-02-16
展开全部
public static string PostRequest(string url, Encoding encoding, Dictionary<string, object> input = null)
{
var request = WebRequest.Create(new Uri(url));
request.Method = System.Net.WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
if (input != null)
{
var builder = new StringBuilder();
foreach (var item in input)
{
var value = HttpUtility.UrlEncode(item.Value.ToString(), encoding);
builder.AppendFormat("{0}={1}&", item.Key, value);
}
var bytesForArray = encoding.GetBytes(builder.ToString());
request.ContentLength = bytesForArray.Length;
var stream = request.GetRequestStream();
stream.Write(bytesForArray, 0, bytesForArray.Length);
stream.Close();
}
var response = request.GetResponse();
var list = new List<byte>();
var buffer = new byte[1024];
int len = 0;
var rStream = response.GetResponseStream();
while ((len = rStream.Read(buffer, 0, buffer.Length)) > 0)
{
list.AddRange(buffer.Take(len));
}
response.Close();
return encoding.GetString(list.ToArray());
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询