【转】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 ...
随机推荐
- 那些年不错的Android开源项目
那些年不错的Android开源项目 转载自 eoe 那些年不错的Android开源项目-个性化控件篇 第一部分 个性化控件(View) 主要介绍那些不错个性化的View,包括ListView.Acti ...
- codeforces Round #263(div2) D. Appleman and Tree 树形dp
题意: 给出一棵树,每个节点都被标记了黑或白色,要求把这棵树的其中k条变切换,划分成k+1棵子树,每颗子树必须有1个黑色节点,求有多少种划分方法. 题解: 树形dp dp[x][0]表示是以x为根的树 ...
- hdu 5752 Sqrt Bo
Sqrt Bo Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total S ...
- subList和asList
subList subList返回仅仅只是一个视图.直接上源码 public List<E> subList(int fromIndex, int toIndex) { subListRa ...
- 使用NGUINGUI的相关介绍
1.3 使用NGUI 要使用NGUI,需要首先为游戏项目导入NGUI插件资源,然后再创建UI Root对象,在这以后才可以添加各种UI控件,下面本节会详解介绍这些知识本文选自NGUI从入门到实战! ...
- C# 中的可变参数方法(VarArgs)
首先需要明确一点:这里提到的可变参数方法,指的是具有 CallingConventions.VarArgs 调用约定的方法,而不是包含 params 参数的方法.可以通过MethodBase.Call ...
- checkbox下面的提示框 鼠标移入时显示,移出时隐藏
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- Windows Phone 硬件检测
private static bool IsWvga{ get { return App.Current.Host.Content.ScaleFactor == 100; }} private sta ...
- c++ map删除元素
typedef std::map<std::string,float> StringFloatMap; StringFloatMap col1; StringFloatMap::itera ...
- 【POJ】1269 Intersecting Lines(计算几何基础)
http://poj.org/problem?id=1269 我会说这种水题我手推公式+码代码用了1.5h? 还好新的一年里1A了---- #include <cstdio> #inclu ...