简单的HttpWebRequest、WebClient 请...

HttpWebRequest小实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTest;
using System.Net;
using System.IO;
using System.Text;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
string url = @"http://app.smartearth.cn/rgc?point=116.395645,39.929986";
// url = @"http://www.baidu.com";
HttpWebRequest request =(HttpWebRequest) HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse result = (HttpWebResponse)request.GetResponse();
Stream stream = null;
stream = result.GetResponseStream();
StreamReader sReader = new StreamReader(stream, Encoding.UTF8);
string outResult = sReader.ReadToEnd();
result.Close();
Response.Write( outResult);
}
}
WebClient 小实例
/// <summary>
/// 取对象地址
/// </summary>
/// <param name="Locality_Longitude">经度</param>
/// <param name="Locality_Latitude">纬度</param>
/// <returns>Address</returns>
public string GetAddress(string Locality_Longitude, string Locality_Latitude)
{
System.Net.WebClient client = new System.Net.WebClient();
string url = "http://app.smartearth.cn/rgc?point=" + Locality_Longitude + "," + Locality_Latitude;
client.Encoding = Encoding.UTF8;
string responseTest = client.DownloadString(url);
string Address = "";
try
{
JsonString sJson = ParseFromJson<JsonString>(responseTest);
Address = sJson.result.point.name;
}
catch
{
Address = @"未找到地址";
}
return Address;
}
/// <summary>
/// 获取Json的Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="szJson"></param>
/// <returns></returns>
public T ParseFromJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
/// <summary>
/// Json对象类
/// </summary>
public class JsonString
{
public class ResultString
{
public class PointString
{
public string name { get; set; }
public string lng { get; set; }
public string lat { get; set; }
}
public PointString point { get; set; }
public string district_text { get; set; }
public string address { get; set; }
public string district { get; set; }
}
public ResultString result { get; set; }
public string status { get; set; }
}
Tags: 

延伸阅读

最新评论

发表评论