C# http 发送post或get请求

时间:2024-11-25 18:08:02
/// <summary>
/// 向服务器提交XML数据
/// </summary>
/// <param name="url">远程访问的地址</param>
/// <param name="data">参数</param>
/// <param name="method">"POST"或者“GET”</param>
/// <returns>远程页面调用结果</returns>
public static string PostDataToServer(string url, string data, string method)
{
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest;
switch (method)
{
case "GET":
request.Method = "GET";
break;
case "POST":
{
request.Method = "POST";
byte[] bdata = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/xml;charset=utf-8";
request.ContentLength = bdata.Length;
Stream streamOut = request.GetRequestStream();
streamOut.Write(bdata, , bdata.Length);
streamOut.Close();
}
break;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamIn = response.GetResponseStream(); StreamReader reader = new StreamReader(streamIn);
string result = reader.ReadToEnd();
reader.Close();
streamIn.Close();
response.Close(); return result;
}

调用:

string url="http://10.1.200.215:2289/aa.ashx";
string data="{
"request": {
"body": {
"ProjectId": ,
"OperateType":
},
"header": {
"accountID": "erwerwer,
"digitalSign":
"reqTime": "",
"serviceName": "ertetre",
"version": ""
}
}
}";
string method="POST";
string res=PostDataToServer(url, data, method);

别的比较好的文章收藏:http://singlepine.cnblogs.com/articles/292661.htmlhttp://www.cnblogs.com/xssxss/archive/2012/07/03/2574554.html