zoukankan      html  css  js  c++  java
  • 后端向服务器发送客户端请求--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

  • 相关阅读:
    5+ App开发Native.js入门指南
    uni-app vue-cli命令行
    本地uni-app原生插件提交云端打包
    编写package.json文件
    生成插件包
    无障碍角色 accessibilityRole (iOS, Android)
    ajax 整理
    Javascript分享笔记
    echarts 横坐标分行展示,以及文字显示顶部
    js总结(11)js作用域
  • 原文地址:https://www.cnblogs.com/cuijl/p/7126884.html
Copyright © 2011-2022 走看看