同步:
public static string Post(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
异步:
public void HttpPost(string Url)
{
try
{
//回收垃圾
GC.Collect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";//这里是POST请求,可以改成GET
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetResponse(new AsyncCallback(Compleate), request);
}
catch
{
Tips(DateTime.Now.ToString("hh:mm:ss") + " 同步连接失败");
}
}
public void Compleate(IAsyncResult asyncResult)
{
try
{
HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest);
HttpWebResponse res = req.EndGetResponse(asyncResult) as HttpWebResponse;
StreamReader reader = new StreamReader(res.GetResponseStream());
Tips(DateTime.Now.ToString("hh:mm:ss") + " 手动同步成功");
}
catch
{
Tips(DateTime.Now.ToString("hh:mm:ss") + " 手动同步失败");
}
}