c# webservice [webmethod] 獲取 json資料(字元流) 以及請求頭 headers 的值
第一次寫部落格,簡單說明以下原因。新手工作半年,用的是C# webservice請求,比較老的技術。有可能我的理解還不是很深,暫且這樣認為把。目前做的專案都是請求別人介面,request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; 定義的傳輸報文體,當然還有其他型別的。但是怎麼接收卻沒做過,網上百度也是沒有明確的回答。下面舉例子。
** 獲得請求的json資料,注意不是json字串。下面程式碼展示(包括header)
HttpResponse Response;
private void setEncoding()
{
Response = HttpContext.Current.Response;
WebClientSelf.setUTF8Encoding(Response);
}
[WebMethod(Description = "帶header的提交json資料")]
public void get()
{
setEncoding();
string result = "";
string name = "{\"code\":\"hellow word!\"}";
byte[] quest = System.Text.Encoding.UTF8.GetBytes(name);
string url = "http://localhost:11263/webservice/common.asmx/A";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("uid", "admin");
request.Headers.Add("pwd", "admin888");
request.ContentLength = quest.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(quest, 0, quest.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
Stream stream = resp.GetResponseStream();
//獲取響應內容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
Response.Write(result);
Response.End();
}
接收方法:
[WebMethod(Description = "獲取實體流")]
public string A()
{
Stream s = HttpContext.Current.Request.InputStream;//獲得json 字元流,
string header = HttpContext.Current.Request.Headers["uid"];//獲得header 下uid的值
//還原資料流
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
string jsontext=Encoding.UTF8.GetString(b);
return "header=" + header + "|" + "json=" + jsontext;
}