接上篇」WCF實現REST服務「,服務端有了,咱們看看客戶端怎麼訪問,因爲JS跨域的限制,這裏經過WebClient作在後臺代理來訪問,話很少說,直接上代碼。 json
一、GET請求 c#
WebClient test = new WebClient(); Stream data = test.OpenRead("http://localhost:8000/api/test/111"); StreamReader reader = null; try { reader = new StreamReader(data, Encoding.UTF8); string responseJson = reader.ReadToEnd(); } finally { try { if (reader != null) { reader.Close(); } } catch { } }
二、POST/PUT/DELETE請求 api
//這裏是傳遞給服務方法的參數,JSON格式,在WCF的接口特性中能夠更改成XML格式~ StringBuilder json = new StringBuilder(); json.Append("{"); json.Append("\"loginName\":\"test\","); json.Append("\"password\":\"test\""); json.Append("}"); byte[] requestData = Encoding.GetEncoding("UTF-8").GetBytes(json.ToString()); WebClient test = new WebClient(); test.Headers.Add("Content-Type", "application/json"); test.Headers.Add("ContentLength", data.Length.ToString()); //例子裏用的是POST方法,要使用PUT/DELETE方法只須要把POST改爲PUT/DELETE就好了~ byte[] responseData = test.UploadData("http://localhost:8000/api/login/", "POST", data); string result = Encoding.GetEncoding("UTF-8").GetString(results);嗯~就這些~歡迎拍磚~可是~能不能別打臉。。。