C# Post和Get请求

Get请求:

 /// <summary>
/// 调用ToxyzAPI
/// </summary>
/// <param name="requetid">リクエストID</param>
/// <param name="serial">車載シリアル</param>
/// <param name="routeid">ルートID</param>
/// <param name="driverId">ドライバーID</param>
/// <returns></returns>
public void SetPC(string requetid, int serial, int routeid, int driverId)
{
//拼接请求的URL
string requestUrl = "http://10.167.218/settoxyz/setPC? oxrequetid" + requetid +
"&oxserial=" + serial.ToString() + "&oxrouteid=" + routeid.ToString() + "&oxdriverid" + driverId.ToString(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "GET";//设置请求方式
request.ContentType = "text/html;charset=UTF-8";
request.Timeout = ;//超时时间
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string result = streamReader.ReadToEnd();//请求结果
streamReader.Close();
responseStream.Close();
}

POST请求:

/// <summary>
/// 调用ToxyzAPI
/// </summary>
/// <param name="requetid">リクエストID</param>
/// <param name="serial">車載シリアル</param>
/// <param name="routeid">ルートID</param>
/// <param name="driverId">ドライバーID</param>
/// <returns></returns>
public void SetPC(string requetid, int serial, int routeid, int driverId)
{
string url = "http://10.167.218.48/settoxyz/setPC";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";//设置请求方式POST
req.ContentType = "application/x-www-form-urlencoded";
#region 添加参数
IDictionary<string, object> requestInfoModel = new Dictionary<string, object>();
requestInfoModel.Add("oxrequetid", requetid);
requestInfoModel.Add("oxserial", serial);
requestInfoModel.Add("oxrouteid", routeid);
requestInfoModel.Add("oxdriverid", driverId);
StringBuilder builder = new StringBuilder();
int i = ;
foreach (var item in requestInfoModel)
{
if (i > )
{
builder.Append("&");
}
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, , data.Length);
reqStream.Close();
}
#endregion HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
上一篇:1.java.io包中定义了多个流类型来实现输入和输出功能,


下一篇:css规范大全