【转】C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据
http://blog.csdn.net/kingcruel/article/details/44036871
版权声明:本文为博主原创文章,未经博主允许不得转载。
- ======================================================================================================================================
- /// <summary>
- /// 日期:2016-2-4
- /// 备注:bug已修改,可以使用
- /// </summary>
- public static void Method1()
- {
- try
- {
- string domain = "http://192.168.1.6:8098/";
- string url = domain + "/Signin/LoginApi";
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ReadWriteTimeout = 30 * 1000;
- ///添加参数
- Dictionary<String, String> dicList = new Dictionary<String, String>();
- dicList.Add("UserName", "test@qq.com");
- dicList.Add("Password", "000000");
- String postStr = buildQueryStr(dicList);
- byte[] data = Encoding.UTF8.GetBytes(postStr);
- request.ContentLength = data.Length;
- Stream myRequestStream = request.GetRequestStream();
- myRequestStream.Write(data, 0, data.Length);
- myRequestStream.Close();
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- var retString = myStreamReader.ReadToEnd();
- myStreamReader.Close();
- }
- catch (Exception ex)
- {
- log.Info("Entered ItemHierarchyController - Initialize");
- log.Error(ex.Message);
- }
- }
- ======================================================================================================================================
升级版本,提取到帮助类,封装对象
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
- namespace CMS.Common
- {
- public class MyHttpClient
- {
- public string methodUrl = string.Empty;
- public string postStr = null;
- public MyHttpClient(String methodUrl)
- {
- this.methodUrl = methodUrl;
- }
- public MyHttpClient(String methodUrl, String postStr)
- {
- ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi
- ///this.postStr = postStr;
- this.methodUrl = methodUrl;
- this.postStr = postStr;
- }
- /// <summary>
- /// GET Method
- /// </summary>
- /// <returns></returns>
- public String ExecuteGet()
- {
- HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
- myRequest.Method = "GET";
- HttpWebResponse myResponse = null;
- try
- {
- myResponse = (HttpWebResponse)myRequest.GetResponse();
- StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
- string content = reader.ReadToEnd();
- return content;
- }
- //异常请求
- catch (WebException e)
- {
- myResponse = (HttpWebResponse)e.Response;
- using (Stream errData = myResponse.GetResponseStream())
- {
- using (StreamReader reader = new StreamReader(errData))
- {
- string text = reader.ReadToEnd();
- return text;
- }
- }
- }
- }
- /// <summary>
- /// POST Method
- /// </summary>
- /// <returns></returns>
- public string ExecutePost()
- {
- string content = string.Empty;
- Random rd = new Random();
- int rd_i = rd.Next();
- String nonce = Convert.ToString(rd_i);
- String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
- String signature = GetHash(this.appSecret + nonce + timestamp);
- try
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.Headers.Add("Nonce", nonce);
- request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));
- request.Headers.Add("Signature", signature);
- request.ReadWriteTimeout = 30 * 1000;
- byte[] data = Encoding.UTF8.GetBytes(postStr);
- request.ContentLength = data.Length;
- Stream myRequestStream = request.GetRequestStream();
- myRequestStream.Write(data, 0, data.Length);
- myRequestStream.Close();
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- content = myStreamReader.ReadToEnd();
- myStreamReader.Close();
- }
- catch (Exception ex)
- {
- }
- return content;
- }
- }
- public class StringProc
- {
- public static String buildQueryStr(Dictionary<String, String> dicList)
- {
- String postStr = "";
- foreach (var item in dicList)
- {
- postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
- }
- postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
- return postStr;
- }
- public static int ConvertDateTimeInt(System.DateTime time)
- {
- System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
- return (int)(time - startTime).TotalSeconds;
- }
- }
- }
前端调用
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using CMS.Common;
- using Newtonsoft.Json;
- namespace Medicine.Web.Controllers
- {
- public class DefaultController : Controller
- {
- public ActionResult Index()
- {
- #region DoGet
- string getResultJson = this.DoGet(url);
- HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));
- #endregion
- #region DoPost
- string name = Request.Form["UserName"];
- string password = Request.Form["Password"];
- Dictionary<String, String> dicList = new Dictionary<String, String>();
- dicList.Add("UserName", name);
- dicList.Add("Password", password);
- string postStr = StringProc.buildQueryStr(dicList);
- string postResultJson = this.DoPost(url, postStr);
- HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));
- #endregion
- return View();
- }
- /// <summary>
- /// GET Method
- /// </summary>
- /// <param name="portraitUri">url地址</param>
- /// <returns></returns>
- private String DoGet(string portraitUri)
- {
- MyHttpClient client = new MyHttpClient(portraitUri);
- return client.ExecuteGet();
- }
- /// <summary>
- /// POST Method
- /// </summary>
- /// <param name="portraitUri">url地址</param>
- /// <param name="postStr">请求参数</param>
- /// <returns></returns>
- private String DoPost(string portraitUri, string postStr)
- {
- MyHttpClient client = new MyHttpClient(portraitUri, postStr);
- return client.ExecutePost();
- }
- public class HttpClientResult
- {
- public string UserName { get; set; }
- public bool Success { get; set; }
- }
- }
- }
【转】C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据的更多相关文章
- RestSharp发送请求得到Json数据
NUGET安装:RestSharp code: public string Post(string url, string content) { string contentType = " ...
- 使用jQuery解析JSON数据(由ajax发送请求到php文件处理数据返回json数据,然后解析json写入html中呈现)
在上一篇的Struts2之ajax初析中,我们得到了comments对象的JSON数据,在本篇中,我们将使用jQuery进行数据解析. 我们先以解析上例中的comments对象的JSON数据为例,然后 ...
- autojs,autojs 发送http请求,autojs 解析json数据
如题,我这个就直接上代码吧 (function () { let request = http.request; // 覆盖http关键函数request,其他http返回最终会调用这个函数 http ...
- 异步POST请求解析JSON
异步POST请求解析JSON 一.创建URL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order ...
- iapp,iapp http请求,iapp解析json数据
iapp发送http请求,并解析json数据 //http操作 t() { s a = "http://wap.baidu.com/" //目标url hs(a, null, nu ...
- C#解析JSON数据
本篇文章主要介绍C#对Json数据的读取. 主要操作过程是: 发送Http请求获取Json数据 把获取的Json数据转换成C#中的类 下面我们以12306火车票余票的数据为例进行切入. 首先来看一下h ...
- C# 解析json数据出现---锘縖
解析json数据的时候出现 - 锘縖,不知道是不是乱码,反正我是不认识这俩字.后来发现是json的 '[' 字符转换的 网上搜了一下,说的是字符集不匹配,把字符集改为GB2312. 一.贴下处理jso ...
- IOS 解析Json数据(NSJSONSerialization)
● 什么是JSON ● JSON是一种轻量级的数据格式,一般用于数据交互 ● 服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除 外) ● JSON的格式很像OC中的字典和数组 ...
- Qt QJson解析json数据
Qt QJson解析json数据 //加载根目录文件 void TeslaManageData::loadRootFolderFiles() { QNetworkAccessManager *mana ...
随机推荐
- hdu 4640(状压dp)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4640 思路:f[i][j]表示一个人状态i下走到j的最小花费,dp[i][j]表示i个人在状态j下的最 ...
- Web开发中运行环境的配置:(Tomcat7.0.59)和开发环境的配置
第一部分:运行环境的配置 1.下载压缩包,解压即可 2.配置系统变量JAVA_HOME为jdk的安装路径 3.如有需要修改端口号,比如8080已被占用的时候,可以将其改为9080等 apache-to ...
- 不能继承OrmLiteBaseActivity时,这样获取getHelper
private DatabaseHelper databaseHelper = null; public DatabaseHelper getHelper() { if (databaseHelper ...
- 直接操作游戏对象C#游戏开发
直接操作游戏对象C#游戏开发 2.2.3 直接操作游戏对象 在Inspector视图里通过设置属性而改变游戏场景中游戏对象的状态,太过抽象,毕竟数字并不够直观.其实,改变游戏对象的状态,完全有最最直 ...
- css 样式 图片平铺整个界面
比如一个容器(body,div,span)中设定一个背景.这个背景的长宽值在css2.1之前是不能被修改的. 所以实际的结果是只能重复显示,所以出现了repeat,repeat-x,repeat-y, ...
- 计算几何 HDOJ 4720 Naive and Silly Muggles
题目传送门 /* 题意:给三个点求它们的外接圆,判断一个点是否在园内 计算几何:我用重心当圆心竟然AC了,数据真水:) 正解以后补充,http://www.cnblogs.com/kuangbin/a ...
- bzoj1030 [JSOI2007]文本生成器
1030: [JSOI2007]文本生成器 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 2654 Solved: 1100[Submit][Stat ...
- 博客搬到blog.csgrandeur.com
博客已搬到blog.csgrandeur.com. cnblogs停止更新. wordpress太臃肿,难刷. hexo对windows似乎不太友好,迁移的时候建了十几层文件夹,导致目录过深无法移动无 ...
- Codeforces Round #203 (Div. 2) A.TL
#include <iostream> #include <algorithm> using namespace std; int main(){ int n,m; cin & ...
- 【wikioi】1913 数字梯形问题(费用流)
http://wikioi.com/problem/1913/ 如果本题没有询问2和3,那么本题和蚯蚓那题一模一样.http://www.cnblogs.com/iwtwiioi/p/3935039. ...