您的位置:首页 > 理论基础 > 计算机网络

C#客户端发送Http请求与服务端通信

2017-12-14 09:40 323 查看


C#客户端发送Http请求与服务端通信


环境介绍

1.软件 vs2013 
2. 编程语言c# winform 
3. 服务端采用java+spring,restful风格

在客户端,通过HttpWebRequest方法,向服务端发送get,post,put和delete请求,但是由于服务端的接收参数不同,以及在具体请求下有稍微的不同,故分为以下几种情况(本文所有代码均为底层接口的形式给出,可以直接被上层具体方法调用)


1.GET请求,服务端接收参数方式为@RequestParam

get请求接收参数的方式通常均为@RequestParam,此时,请求参数实际上是以 “url?param1=xx¶m2=xx”的形式传递的,所以代码如下
//url为请求的网址,param参数为需要查询的条件(服务端接收的参数,没有则为null)
//返回该次请求的响应
public string GET(string url,Dictionary<String,String> param)
{
if(param!=null) //有参数的情况下,拼接url
{
url = url + "?";
foreach (var item in param)
{
url = url + item.Key + "=" + item.Value+"&";
}
url = url.Substring(0, url.Length - 1);
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求
request.Method = "GET"; //请求方法为GET
HttpWebResponse res; //定义返回的response
try
{
res = (HttpWebResponse)request.GetResponse(); //此处发送了请求并获得响应
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //响应转化为String字符串
return content;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


2.POST(PUT)请求,服务端接收参数方式为@RequestParam

当在post或者put请求以@RequestParam接收参数时,实际提交参数的形式是类似于表单提交,这种情况下,每一个提交的参数前都需要添加boundary,用于将不同的参数分开,具体的提交方式可以参考我的另一篇文章:C#上传文件到服务端(http://blog.csdn.net/pinebud55/article/details/52182217


3.POST(PUT)请求,服务端接收参数方式为@RequestBody

对于post请求,除非上传文件的特殊情况,否则我们推荐服务端以requestbody形式接收参数,因为在需要接受的参数较多时,代码可以更加简洁,并且不再需要后期增加接收的参数,body即包含了一个对象所有的属性。

言归正传,这种情况的处理是最理想的,只需要将需要提交的参数以json的方式提交即可,代码如下:
//url为请求的网址,param为需要传递的参数
//返回服务端的额响应
public string POST(string url, Dictionary<String, String> param)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
//request.AllowReadStreamBuffering = true;
request.MaximumResponseHeadersLength = 1024;
request.Method = "POST"; //请求方式为post
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = 1024;
request.ContentType = "application/json";
JObject json = new JObject();
if(param.Count!=0) //将参数添加到json对象中
{
foreach(var item in param)
{
json.Add(item.Key, item.Value);
}
}
string jsonstring = json.ToString();//获得参数的json字符串
byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, 0, jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //获得响应字符串
return content;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: