http调用webservice操作httprequest、httpresponse示例
rest wcf 使得我们调用web服务时,可以通过httprequest的交互简单完成。那么老版的webservice能否做到呢?webservice中通过httpcontext.current.rquest/response,我们一样也可以改造webmethod。
客户端:
// 创建一个datatable
datatable data = new datatable("project");
data.columns.add("name");
data.columns.add("birthday");
data.rows.add(new object[] { "wendy", "1978/03/11" });
data.rows.add(new object[] { "philip", "2000/11/05" });
data.rows.add(new object[] { "felix", "1999/08/04" });
using (var ms = new memorystream())
{
// 将datatable用xml格式写入流
data.writexml(ms, xmlwritemode.writeschema);
var client = new webclient();
// 定义httprequest的content-type(xml,json等)
client.headers.add("content-type", "text/xml");
var url = "http://localhost:2609/service1.asmx/sendxml";
// send httprequest
var resp = client.uploaddata(url, "post", ms.toarray());
var strresp = system.text.encoding.utf8.getstring(resp);
messagebox.show(strresp);
}
服务端:
[webmethod]
public void sendxml()
{
// 获得客户端raw httprequest
var inputstream = httpcontext.current.request.inputstream;
// 定义response返回的格式是:json
var response = httpcontext.current.response;
response.contenttype = "text/json";
//var strxml = "";
//using (var sr = new streamreader(inputstream))
// strxml = sr.readtoend();
try
{
datatable data = new datatable();
using (var xr = xmlreader.create(inputstream))
data.readxml(xr);
// 将读入xml的datatable的行数返回客户端
string count = "/"" + data.rows.count + "/"";
response.binarywrite(system.text.encoding.utf8.getbytes(count));
}
catch (exception ex)
{
response.binarywrite(system.text.encoding.utf8.getbytes(ex.message));
}
}
客户端输出""3""
ps: 如果客户端的httprequest满足soap序列化格式,webservice会为webmethod将消息反序列化成参数。相对应的客户端代理类也是通过将消息反序列化成对象供客户端使用。
上一篇: 使用IDEA创建Java Web项目并部署访问的图文教程
下一篇: MySQL索引之主键索引