后端向服务器发送客户端请求--HttpWebRequest

HttpWebRequest类与HttpRequest类的区别

HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所有信息。

HttpWebRequest用于客户端,拼接请求的HTTP报文并发送等。它封装了几乎HTTP请求报文里需要用到的东西,以致于能够能够发送任意的HTTP请求并获得服务器响应(Response)信息。采集信息常用到这个类

 1 private ApiResultModel GetDataByProductIdInApi(int ProductID)
 2     {
 3         ApiResultModel model = null;
 4         string url = "http://localhost:9001/West/ProductDZ/InfoPreView/" + ProductID;
 5     //HttpWebRequest实力需要使用Create创建,然后设置一些参数
 6         HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
 7         request.Method = "Get";
 8         request.ContentType = "application/json";
 9     //需要注意的是因为是异端请求所以需要trycatch释放异常及处理        
10     try
11         {
12             WebResponse response = request.GetResponse()
13             //流对象需要手工释放对象
14                 using (Stream stream = response.GetResponseStream())
15                 {
16                     using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
17                     {
18                         model = new ApiResultModel();
19                         model = JsonConvert.DeserializeObject<ApiResultModel>(reader.ReadToEnd());
20                     }
21                 }
22             
23             return model;
24         }
25         catch (Exception)
26         {
27             request.Abort();
28         }
29         finally
30         {
31             request.Abort();
32         }
33         return null;
34     }

内部使用了Newton.js是解析json对象,需要创建与服务器想通的model类

HttpWebRequest功能比较强大,也可以实现post提交数据及上传or下载数据

post操作可参考:http://www.cnblogs.com/kissdodog/archive/2013/04/06/3002779.html

转载于:https://www.cnblogs.com/cuijl/p/7126884.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值