c# 发送web请求
2024-10-21 03:06:21
我们目前涉及到的现有的接收请求方式有三种,
第一种:
页面式的Form表单
第二种:
服务的webservice形式的xml
第三个:
restful风格的post包体json
第一种比较老,博客园的登录就是这样的。找了个例子
这里不做具体讨论了。
例子
List<KeyValuePair<string, string>> paramList = new List<KeyValuePair<string, string>>();
HttpClient _client = new HttpClient(); async void DownloadPageAsync()
{
// Use static HttpClient to avoid exhausting system resources for network connections.
var result = await _client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList));
// Write status code.
Console.WriteLine("STATUS CODE: " + result.StatusCode);
result.EnsureSuccessStatusCode();
string resultStr = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultStr);
}
DownloadPageAsync();
第二种的,webservice的,之前的博客里有。
第三种,比较新的json的请求方式
针对这种,就只能用json字符串来提交了,具体代码是
string url = getPRC_Url(serviceName, apiName, null);
string body = "{";
//如果需要POST数据
if (!(parameters == null || parameters.Count == ))
{
StringBuilder buffer = new StringBuilder();
foreach (string key in parameters.Keys)
{
buffer.AppendFormat("\"{0}\":\"{1}\",", key, parameters[key]);
}
body += buffer.ToString() + "}";
}
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = ;
byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();
return responseContent;
}
catch (Exception ex)
{
return null;
}
主要是这个入参需要放在包体里,并且得是"{}"形式的方可。
最新文章
- oracle 11g dmp文件导入10g
- python解析json
- codeforces 719E E. Sasha and Array(线段树)
- 初次接触Groovy
- logback详细配置(三)
- Python闭包与javascript闭包比较
- Java中RMI框架
- 纪念一下第一次写的django代码
- Codeforces Round #216 (Div. 2) D. Valera and Fools
- angular.js的路由和模板在asp.net mvc 中的使用
- jquery 学习笔记 (2)--write less,do more
- 再起航,我的学习笔记之JavaScript设计模式21(命令模式)
- Chrome扩展插件流程
- Structured Streaming Programming Guide结构化流编程指南
- linux 共享内存的理解
- EF6 学习笔记(三):排序、过滤查询及分页
- System.ServiceProcess.TimeoutException: Time out has expired and the operation has not been completed.
- 图解FTP服务器搭建(Windows Server 2008)
- part1:5Linux命令详解
- WDCP上传SSL证书