.net post请求webservice
程序员文章站
2022-05-03 10:41:56
class Program { static void Main(string[] args) { var m = "m=" + JsonConvert.SerializeObject(new { age = 1, name = "jxp" }); var a = HttpHelper.PostRe ......
class program { static void main(string[] args) { var m = "m=" + jsonconvert.serializeobject(new { age = 1, name = "jxp" }); var a = httphelper.postrequest("http://localhost:7132/jxp.asmx/helloworld", datatypeenum.form, m); var xmldoc = new xmldocument(); xmldoc.loadxml(a); var nsmgr = new xmlnamespacemanager(xmldoc.nametable); nsmgr.addnamespace("ns", "http://tempuri.org/"); xmlnode errornode = xmldoc.selectsinglenode("/ns:string", nsmgr); var b = jsonconvert.deserializeobject(errornode.innertext); console.writeline(b); console.readkey(); } }
[webmethod] public string helloworld(string m) { return m; }
public class httphelper { /// <summary> /// post带参请求 /// </summary> /// <param name="url"></param> /// <param name="contenttype">指定参数类型</param> /// <param name="strdata"></param> /// <param name="dicheader"></param> /// <returns></returns> public static string postrequest(string url, datatypeenum contenttype, string strdata, dictionary<string, string> dicheader = null) { string result; var webrequest = webrequest.create(url); if (dicheader != null) foreach (var m in dicheader) { webrequest.headers.add(m.key, m.value); } webrequest.method = methodtypeenum.post.tostring(); webrequest.proxy = null; if (contenttype == datatypeenum.form) { webrequest.contenttype = "application/x-www-form-urlencoded"; } else { webrequest.contenttype = "application/" + contenttype; } byte[] reqbodybytes = system.text.encoding.utf8.getbytes(strdata); stream reqstream = webrequest.getrequeststream();//加入需要发送的参数 reqstream.write(reqbodybytes, 0, reqbodybytes.length); reqstream.close(); using (var reader = new streamreader(webrequest.getresponse().getresponsestream())) { result = reader.readtoend(); } return result; } /// <summary> /// get不带参请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string getrequest(string url) { string result; webrequest webrequest = webrequest.create(url); webrequest.method = methodtypeenum.get.tostring(); webrequest.proxy = null; using (var reader = new streamreader(webrequest.getresponse().getresponsestream())) { result = reader.readtoend(); } return result; } } /// <summary> /// 带参数据类型 /// </summary> public enum datatypeenum { json, xml, form } /// <summary> /// 带参数据类型 /// </summary> public enum methodtypeenum { get, post }
返回json
上一篇: C#上手练习6(方法语句1)