一、.net2.0 自带的WebClient请求,不带cookie,需要从写
1、post请求
/// <summary>
/// Posts the specified URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="data">The data.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="headers">The headers.</param>
/// <returns></returns>
public static string Post(string url, string data, string contentType, NameValueCollection headers = null)
{
string result = "";
try
{
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = contentType;
client.Headers[HttpRequestHeader.Accept] = " text/html, */*";
client.Headers[HttpRequestHeader.AcceptCharset] = "GBK";
client.Headers[HttpRequestHeader.AcceptLanguage] = "zh-cn";
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/3.0 (compatible; Indy Library)";
if (headers != null)
{
for (int i = 0; i < headers.Count; i++)
{
client.Headers.Set(headers.AllKeys[i], headers[i]);
}
}
result = client.UploadString(url, "POST", data);
}
}
catch (WebException wex)
{
throw wex;
}
catch (Exception ex)
{
throw ex;
}
return result;
}
2、get 请求
public static string GetData(string url, NameValueCollection headers = null)
{
string result = "";
try
{
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
if (headers != null)
{
for (int i = 0; i < headers.Count; i++)
{
client.Headers.Set(headers.AllKeys[i], headers[i]);
}
}
result = client.DownloadString(url);
}
}
catch (WebException wex)
{
throw wex;
}
catch (Exception ex)
{
throw ex;
}
return result;
}
二、httpclient 请求,自带cookie。
1、get 请求
var s = http.GetStringAsync(geturl).Result;
2、post请求
Template template = new Template();
template.TemplateContent = Properties.Resources.EnterpriseHead;
template.Set("nsr", nsr);
template.Set("djxh", DjxhChache[nsrsbh]);
string tycxparam = template.Render();
Dictionary<string, string> dictionary = new Dictionary<string, string>()
{
{ "bizXml",tycxparam},
{ "sid","id"},
{ "action","queryData"}
};
var request = http.PostAsync(url, new FormUrlEncodedContent(dictionary)).Result;