• 【转】C# HttpWebRequestHttpWebResponseWebClient发送请求解析json数据


    http://blog.csdn.net/kingcruel/article/details/44036871

    [csharp] view plain copy
     
    1. ======================================================================================================================================  
    2. /// <summary>  
    3. /// 日期:2016-2-4  
    4. /// 备注:bug已修改,可以使用  
    5. /// </summary>  
    6. public static void Method1()  
    7. {  
    8.     try  
    9.     {  
    10.         string domain = "http://192.168.1.6:8098/";  
    11.         string url = domain + "/Signin/LoginApi";  
    12.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  
    13.         request.Method = "POST";  
    14.         request.ContentType = "application/x-www-form-urlencoded";  
    15.         request.ReadWriteTimeout = 30 * 1000;  
    16.   
    17.         ///添加参数  
    18.         Dictionary<String, String> dicList = new Dictionary<String, String>();  
    19.         dicList.Add("UserName", "test@qq.com");  
    20.         dicList.Add("Password", "000000");  
    21.         String postStr = buildQueryStr(dicList);  
    22.         byte[] data = Encoding.UTF8.GetBytes(postStr);  
    23.   
    24.         request.ContentLength = data.Length;  
    25.   
    26.         Stream myRequestStream = request.GetRequestStream();  
    27.         myRequestStream.Write(data, 0, data.Length);  
    28.         myRequestStream.Close();  
    29.   
    30.         HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
    31.         StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    32.         var retString = myStreamReader.ReadToEnd();  
    33.         myStreamReader.Close();  
    34.     }  
    35.     catch (Exception ex)  
    36.     {  
    37.         log.Info("Entered ItemHierarchyController - Initialize");  
    38.         log.Error(ex.Message);  
    39.     }  
    40. }  
    41. ======================================================================================================================================  

    升级版本,提取到帮助类,封装对象

    [csharp] view plain copy
     
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Configuration;  
    4. using System.IO;  
    5. using System.Net;  
    6. using System.Text;  
    7. using System.Web;  
    8.   
    9. namespace CMS.Common  
    10. {  
    11.     public class MyHttpClient  
    12.     {  
    13.         public string methodUrl = string.Empty;  
    14.         public string postStr = null;  
    15.   
    16.         public MyHttpClient(String methodUrl)  
    17.         {  
    18.             this.methodUrl = methodUrl;  
    19.         }  
    20.   
    21.         public MyHttpClient(String methodUrl, String postStr)  
    22.         {  
    23.             ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi  
    24.             ///this.postStr = postStr;  
    25.   
    26.             this.methodUrl = methodUrl;  
    27.             this.postStr = postStr;  
    28.         }  
    29.   
    30.         /// <summary>  
    31.         /// GET Method  
    32.         /// </summary>  
    33.         /// <returns></returns>  
    34.         public String ExecuteGet()  
    35.         {  
    36.             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);  
    37.             myRequest.Method = "GET";  
    38.   
    39.             HttpWebResponse myResponse = null;  
    40.             try  
    41.             {  
    42.                 myResponse = (HttpWebResponse)myRequest.GetResponse();  
    43.                 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);  
    44.                 string content = reader.ReadToEnd();  
    45.                 return content;  
    46.             }  
    47.             //异常请求  
    48.             catch (WebException e)  
    49.             {  
    50.                 myResponse = (HttpWebResponse)e.Response;  
    51.                 using (Stream errData = myResponse.GetResponseStream())  
    52.                 {  
    53.                     using (StreamReader reader = new StreamReader(errData))  
    54.                     {  
    55.                         string text = reader.ReadToEnd();  
    56.   
    57.                         return text;  
    58.                     }  
    59.                 }  
    60.             }  
    61.         }  
    62.   
    63.         /// <summary>  
    64.         /// POST Method  
    65.         /// </summary>  
    66.         /// <returns></returns>  
    67.         public string ExecutePost()  
    68.         {  
    69.             string content = string.Empty;  
    70.   
    71.             Random rd = new Random();  
    72.             int rd_i = rd.Next();  
    73.             String nonce = Convert.ToString(rd_i);  
    74.             String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));  
    75.             String signature = GetHash(this.appSecret + nonce + timestamp);  
    76.   
    77.             try  
    78.             {  
    79.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);  
    80.                 request.Method = "POST";  
    81.                 request.ContentType = "application/x-www-form-urlencoded";  
    82.                 request.Headers.Add("Nonce", nonce);  
    83.                 request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));  
    84.                 request.Headers.Add("Signature", signature);  
    85.                 request.ReadWriteTimeout = 30 * 1000;  
    86.   
    87.                 byte[] data = Encoding.UTF8.GetBytes(postStr);  
    88.                 request.ContentLength = data.Length;  
    89.   
    90.                 Stream myRequestStream = request.GetRequestStream();  
    91.   
    92.                 myRequestStream.Write(data, 0, data.Length);  
    93.                 myRequestStream.Close();  
    94.   
    95.                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
    96.                 StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
    97.                 content = myStreamReader.ReadToEnd();  
    98.                 myStreamReader.Close();  
    99.             }  
    100.             catch (Exception ex)  
    101.             {  
    102.             }  
    103.             return content;  
    104.         }  
    105.     }  
    106.   
    107.     public class StringProc  
    108.     {  
    109.         public static String buildQueryStr(Dictionary<String, String> dicList)  
    110.         {  
    111.             String postStr = "";  
    112.   
    113.             foreach (var item in dicList)  
    114.             {  
    115.                 postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";  
    116.             }  
    117.             postStr = postStr.Substring(0, postStr.LastIndexOf('&'));  
    118.             return postStr;  
    119.         }  
    120.   
    121.         public static int ConvertDateTimeInt(System.DateTime time)  
    122.         {  
    123.             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));  
    124.             return (int)(time - startTime).TotalSeconds;  
    125.         }  
    126.     }  
    127. }  

    前端调用
    [csharp] view plain copy
     
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using CMS.Common;  
    7. using Newtonsoft.Json;  
    8.   
    9. namespace Medicine.Web.Controllers  
    10. {  
    11.     public class DefaultController : Controller  
    12.     {  
    13.         public ActionResult Index()  
    14.         {  
    15.             #region DoGet  
    16.   
    17.             string getResultJson = this.DoGet(url);  
    18.             HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));  
    19.  
    20.             #endregion  
    21.  
    22.             #region DoPost  
    23.   
    24.             string name = Request.Form["UserName"];  
    25.             string password = Request.Form["Password"];  
    26.   
    27.             Dictionary<String, String> dicList = new Dictionary<String, String>();  
    28.             dicList.Add("UserName", name);  
    29.             dicList.Add("Password", password);  
    30.             string postStr = StringProc.buildQueryStr(dicList);  
    31.   
    32.             string postResultJson = this.DoPost(url, postStr);  
    33.             HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));  
    34.  
    35.             #endregion  
    36.   
    37.             return View();  
    38.         }  
    39.   
    40.         /// <summary>  
    41.         /// GET Method  
    42.         /// </summary>  
    43.         /// <param name="portraitUri">url地址</param>  
    44.         /// <returns></returns>  
    45.         private String DoGet(string portraitUri)  
    46.         {  
    47.             MyHttpClient client = new MyHttpClient(portraitUri);  
    48.             return client.ExecuteGet();  
    49.         }  
    50.   
    51.         /// <summary>  
    52.         /// POST Method  
    53.         /// </summary>  
    54.         /// <param name="portraitUri">url地址</param>  
    55.         /// <param name="postStr">请求参数</param>  
    56.         /// <returns></returns>  
    57.         private String DoPost(string portraitUri, string postStr)  
    58.         {  
    59.             MyHttpClient client = new MyHttpClient(portraitUri, postStr);  
    60.             return client.ExecutePost();  
    61.         }  
    62.   
    63.         public class HttpClientResult  
    64.         {  
    65.             public string UserName { get; set; }  
    66.   
    67.             public bool Success { get; set; }  
    68.         }  
    69.     }  
    70. }  

     
     
  • 相关阅读:
    VC 使用json cpp 静态库 问题解决
    <转>c++ builder JSONCPP 注意事项 XE2 解决编译问题 _Mfl
    窥探try ... catch与__try ... __except的区别
    二叉树与其它树
    《DirectX 9.0 3D游戏开发编程基础》 第二章 绘制流水线 读书笔记
    《DirectX 9.0 3D游戏开发编程基础》 第一章 初始化Direct3D 读书笔记
    《DirectX 9.0 3D游戏开发编程基础》必备的数学知识 读书笔记
    windows lua 多线程 线程同步
    <转>多线程中的lua同步问题
    php 检查email电子邮件函数(奇葩写法)
  • 原文地址:https://www.cnblogs.com/mimime/p/5998680.html
Copyright © 2020-2023  润新知