标签:
最近项目上在做钉钉开发中,经常会遇到使用post方式调用钉钉内部的方法(微信也有一样),这里涉及到跨域的post调用,但跨域一般都是用jsonp格式,而这个格式只支持get方式。尝试了挺多方法都没有返回
{"errcode":43002,"errmsg":"需要POST请求"}
让人很费解,用js方式不行,只能尝试从后台解决问题,然后写了如下方法:
/// <summary> /// /// </summary> /// <param name="postUrl">post地址</param> /// <param name="paramData">参数</param> /// <param name="dataEncode">数据格式</param> /// <returns></returns> public static string HttpPost(string postUrl, string paramData, Encoding dataEncode) { string ret = string.Empty; try { byte[] byteArray = dataEncode.GetBytes(paramData); //转化 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); webReq.Method = "POST"; webReq.ContentType = "application/json; charset=utf-8"; webReq.ContentLength = byteArray.Length; Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length);//写入参数 newStream.Close(); HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode); ret = sr.ReadToEnd(); sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { return ex.Message; } return ret; }
测试了下还真行,所以记录下。前面的建立连接,获取access_token等就不多说,官网文档很全面。
标签:
原文地址:http://www.cnblogs.com/xiangzhong/p/5753118.html