接上篇”WCF实现REST服务“,服务端有了,我们看看客户端怎么访问,由于JS跨域的限制,这里通过WebClient做在后台代理来访问,话不多说,直接上代码。
1、GET请求
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
{ }
}
2、POST/PUT/DELETE请求
//这里是传递给服务方法的参数,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);
嗯~就这些~欢迎拍砖~但是~能不能别打脸。。。