首页 > 代码库 > C# Post和Get请求

C# Post和Get请求

Get请求:

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

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 = 0;
    foreach (var item in requestInfoModel)
    {
        if (i > 0)
        {
            builder.Append("&");
        }
        builder.AppendFormat("{0}={1}", item.Key, item.Value);
        i++;
    }
    byte[] data =http://www.mamicode.com/ Encoding.UTF8.GetBytes(builder.ToString());
    req.ContentLength = data.Length;
    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(data, 0, 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();
    }
}

 

C# Post和Get请求