【C#MVC】 使用HttpWebRequest访问外部API,并返回json信息 (Access_Key)
2016-08-25 11:31
931 查看
在c#中调用外部API或者自己系统的API都是很简单的,这里提供使用HttpWebRequest的方式访问外部API,自定义了头部Access_key.
若外部系统没有此安全验证,可以去掉。
若外部系统没有此安全验证,可以去掉。
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post"; request.Headers.Add("access_key", "your access_key"); request.Accept = "application/json"; request.ContentType = "application/json; charset=utf-8"; byte[] buffer = Encoding.ASCII.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) //System.Text.Encoding.GetEncoding(strEncoding) { return reader.ReadToEnd(); } }
相关文章推荐
- [转]C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现
- C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现
- 关于loadrunner使用web_add_header添加HTTP信息头(比如Content-Type,token等)和使用web_custom_request()提交json数据
- C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现方法
- 使用C#的HttpWebRequest访问网站
- C#通过构造Soap信息使用HttpWebRequest调用WebService
- 关于loadrunner使用web_add_header添加HTTP信息头(比如Content-Type,token等)和使用web_custom_request()提交json数据
- C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现
- C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现方法
- C#使用HttpWebRequest POST或GET信息
- C#在WinForm下使用HttpWebRequest上传文件并显示进度
- C#使用WebRequest(HttpRequest)发送文件
- 用C#使用HttpWebRequest Post数据时如何保持Session
- C# 使用HttpWebRequest提交ASP.NET表单并保持Session和Cookie
- C#在WinForm下使用HttpWebRequest上传文件并显示进度
- C#使用浏览器(Internet Explorer)默认的代理服务器设置(WebRequest,WebClient,HttpWebRequest)
- c#中HttpWebRequest使用Proxy实现指定IP的域名请求
- c#使用HttpWebRequest上传文件
- [C#]使用HttpWebRequest请求远端服务器时如何加载SSL证书
- 使用 HttpWebRequest 类调用 WEB 服务的示例(C#) 转