C# Get方式请求Http

 
  

rivate static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

///


/// 创建GET方式的HTTP请求
///

/// 请求的URL
/// 请求的超时时间
/// 请求的客户端浏览器信息,可以为空
/// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空
///
public static string CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
return responseText;

}

将指定的JSON字符串转换为 T 类型的对象
添加引用:System.Web.Extensions 
 添加命名空间:using System.Web.Script.Serialization;
 
   

///

/// 将指定的 JSON 字符串转换为 T 类型的对象。
///


/// 所生成对象的类型。
/// 要进行反序列化的 JSON 字符串。
/// 反序列化失败时返回的默认值。
/// 反序列化的对象。
public static T JosnDeserialize<T>(string input, T def)
{
if (string.IsNullOrEmpty(input))
return def;
try
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
return jsSerializer.Deserialize<T>(input);
}
catch (InvalidOperationException)
{
return def;
}
}

Http请求调用
 
   

 

///


/// 激活信息
///

[Serializable()]
public class ResultInfo
{
///
/// 0 失败;1 成功
///

public int flag { get; set; }

///
/// 执行消息
///

public string msg { get; set; }

}

string strGetUrl = strParmUrl+"?" + strParamValue;

CookieCollection cookies = new CookieCollection();//如何从response.Headers["Set-Cookie"];中获取并设置CookieCollection的代码略
string strResult = HttpHelpTools.CreateGetHttpResponse(strGetUrl, null, null, cookies);
ResultInfoitem = JosnDeserialize<ResultInfo>(strResult, null);

你可能感兴趣的:(windows,编程)