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

版权声明:本文为博主原创文章,未经博主允许不得转载。

  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. Dictionary<String, String> dicList = new Dictionary<String, String>();
  18. dicList.Add("UserName", "test@qq.com");
  19. dicList.Add("Password", "000000");
  20. String postStr = buildQueryStr(dicList);
  21. byte[] data = Encoding.UTF8.GetBytes(postStr);
  22. request.ContentLength = data.Length;
  23. Stream myRequestStream = request.GetRequestStream();
  24. myRequestStream.Write(data, 0, data.Length);
  25. myRequestStream.Close();
  26. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  27. StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  28. var retString = myStreamReader.ReadToEnd();
  29. myStreamReader.Close();
  30. }
  31. catch (Exception ex)
  32. {
  33. log.Info("Entered ItemHierarchyController - Initialize");
  34. log.Error(ex.Message);
  35. }
  36. }
  37. ======================================================================================================================================

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

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

前端调用

  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. namespace Medicine.Web.Controllers
  9. {
  10. public class DefaultController : Controller
  11. {
  12. public ActionResult Index()
  13. {
  14. #region DoGet
  15. string getResultJson = this.DoGet(url);
  16. HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));
  17. #endregion
  18. #region DoPost
  19. string name = Request.Form["UserName"];
  20. string password = Request.Form["Password"];
  21. Dictionary<String, String> dicList = new Dictionary<String, String>();
  22. dicList.Add("UserName", name);
  23. dicList.Add("Password", password);
  24. string postStr = StringProc.buildQueryStr(dicList);
  25. string postResultJson = this.DoPost(url, postStr);
  26. HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));
  27. #endregion
  28. return View();
  29. }
  30. /// <summary>
  31. /// GET Method
  32. /// </summary>
  33. /// <param name="portraitUri">url地址</param>
  34. /// <returns></returns>
  35. private String DoGet(string portraitUri)
  36. {
  37. MyHttpClient client = new MyHttpClient(portraitUri);
  38. return client.ExecuteGet();
  39. }
  40. /// <summary>
  41. /// POST Method
  42. /// </summary>
  43. /// <param name="portraitUri">url地址</param>
  44. /// <param name="postStr">请求参数</param>
  45. /// <returns></returns>
  46. private String DoPost(string portraitUri, string postStr)
  47. {
  48. MyHttpClient client = new MyHttpClient(portraitUri, postStr);
  49. return client.ExecutePost();
  50. }
  51. public class HttpClientResult
  52. {
  53. public string UserName { get; set; }
  54. public bool Success { get; set; }
  55. }
  56. }
  57. }
 
 

【转】C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据的更多相关文章

  1. RestSharp发送请求得到Json数据

    NUGET安装:RestSharp code: public string Post(string url, string content) { string contentType = " ...

  2. 使用jQuery解析JSON数据(由ajax发送请求到php文件处理数据返回json数据,然后解析json写入html中呈现)

    在上一篇的Struts2之ajax初析中,我们得到了comments对象的JSON数据,在本篇中,我们将使用jQuery进行数据解析. 我们先以解析上例中的comments对象的JSON数据为例,然后 ...

  3. autojs,autojs 发送http请求,autojs 解析json数据

    如题,我这个就直接上代码吧 (function () { let request = http.request; // 覆盖http关键函数request,其他http返回最终会调用这个函数 http ...

  4. 异步POST请求解析JSON

    异步POST请求解析JSON 一.创建URL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order ...

  5. iapp,iapp http请求,iapp解析json数据

    iapp发送http请求,并解析json数据 //http操作 t() { s a = "http://wap.baidu.com/" //目标url hs(a, null, nu ...

  6. C#解析JSON数据

    本篇文章主要介绍C#对Json数据的读取. 主要操作过程是: 发送Http请求获取Json数据 把获取的Json数据转换成C#中的类 下面我们以12306火车票余票的数据为例进行切入. 首先来看一下h ...

  7. C# 解析json数据出现---锘縖

    解析json数据的时候出现 - 锘縖,不知道是不是乱码,反正我是不认识这俩字.后来发现是json的 '[' 字符转换的 网上搜了一下,说的是字符集不匹配,把字符集改为GB2312. 一.贴下处理jso ...

  8. IOS 解析Json数据(NSJSONSerialization)

    ● 什么是JSON ● JSON是一种轻量级的数据格式,一般用于数据交互 ● 服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除 外) ● JSON的格式很像OC中的字典和数组 ...

  9. Qt QJson解析json数据

    Qt QJson解析json数据 //加载根目录文件 void TeslaManageData::loadRootFolderFiles() { QNetworkAccessManager *mana ...

随机推荐

  1. dp核心问题研究-从入门到放弃

    首先从数字三角形开始 这个题的特点是..本身遍历次序就是个树型的 每次的决策都已经给定,左下或者右下 并且当我们纠结于是往左下走还是往右下走的时候,每次根据当前的情况贪心都为时尚早,因为后面的数据可以 ...

  2. 【poi】用POI新建一个xlsx文件【或者说将数据存入到xlsx中】/【将数据从xlsx中获取到项目中】

    第一部分:写入xlsx中 使用POI创建一个xlsx文件: 项目结构如下: 具体使用的POI中的 XSSFWorkbook   xlsx对象 Sheet 工作簿对象 Row 行对象 Cell  单元格 ...

  3. js:数据结构笔记3--栈

    栈是一种特殊的列表,数据结构为LIFO: 定义: function Stack() { this.dataStore = []; this.top = 0; this.push = push; thi ...

  4. Div 添加阴影

    <style type="text/css">.mydiv{   width:250px;height:auto;border:#909090 1px solid;ba ...

  5. ubuntu桌面进不去,我跪了

    ubuntu12.04 输入密码正确,但仍然跳回到登陆界面,实在受不了啊! 不知道bug再哪里,但是有个方法真是屡试不爽啊.. ctrl+alt+f1切换到字符界面 /home/xxx/.Xautho ...

  6. BZOJ1397 : Ural 1486 Equal squares

    二分答案mid,然后检验是否存在两个相同的mid*mid的正方形 检验方法: 首先对于每个位置,求出它开始长度为mid的横行的hash值 然后对于hash值再求一次竖列的hash值 将第二次求出的ha ...

  7. HDU 1241 (DFS搜索+染色)

    题目链接:  http://acm.hdu.edu.cn/showproblem.php?pid=1241 题目大意:求一张地图里的连通块.注意可以斜着连通. 解题思路: 八个方向dfs一遍,一边df ...

  8. TYVJ P1082 找朋友 Label:字符串

    描述 童年的我们,对各种事物充满了好奇与向往.这天,小朋友们对数字产生了兴趣,并且想和数字交朋友.可是,怎么分配这些数字才能使得每个小朋友都唯一地找到一个数字朋友呢?C小朋友说:咱们按自己名字的字典序 ...

  9. 使用freemarker生成word,步骤详解并奉上源代码

    1.   步骤 1.    用word编辑好模板 1. 普通字符串替换为 ${string} 2. 表格循环用标签 <#list userList as user> 姓名:${user.u ...

  10. [zt]不到最后一秒你永远不知道结局且震撼你心灵的高端电影

    总有一部电影,让你憋着尿直到看完~~~ http://share.renren.com/share/230538513/17679574169?from=0101090202&shfrom=0 ...