客户端与服务端Post报文构造请求及Http Post与Get请求方法
客户端
namespace Client.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { string url = ""; // 这里我们还不知道服务器的url,因此留空 #region 构造POST请求 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Host = "localhost:14340"; string body = "client_id=123&redirect_uri="+url+"&response_type=code"; byte[] bodyBytes = Encoding.UTF8.GetBytes(body); Stream requestStream = request.GetRequestStream(); requestStream.Write(bodyBytes,0,bodyBytes.Length); #endregion #region 发送请求并取得响应 // 必须使用HttpWebRequest.GetResponse()方法,请求才能被发送并取得响应 HttpWebResponse response = request.GetResponse() as HttpWebResponse; StreamReader sr = new StreamReader(response.GetResponseStream()); ViewBag.Response = sr.ReadToEnd(); #endregion return View(); } } }
服务器端
namespace Server.Models { /// <summary> /// 对于POST请求,必须对请求体的所有参数建立一个模型类。 /// </summary> public class RequestArgs { public string client_id { get; set; } public string redirect_uri { get; set; } public string response_type { get; set; } } } namespace Server.Controllers { public class ApiTestController : ApiController { public HttpResponseMessage Post(RequestArgs args) { string client_id = args.client_id; string redirect_uri = args.redirect_uri; string response_type = args.response_type; return Request.CreateResponse(HttpStatusCode.OK, "I have received your message. Client_id = "+client_id+", RedirectUri = "+redirect_uri+"response_type = "+response_type); } } }
private string HttpPost(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] data = Encoding.UTF8.GetBytes(postDataStr); request.ContentLength = data.Length; Stream myRequestStream = request.GetRequestStream(); myRequestStream.Write(data, 0, data.Length); myRequestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } public string HttpGet(string Url, string urlParams = null) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (string.IsNullOrEmpty(urlParams) ? "" : "?") + urlParams); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。