首页 > 代码库 > C#模拟http 发送post或get请求
C#模拟http 发送post或get请求
/// <summary>
/// 根据经纬度获取城市名称
/// </summary>
/// <param name="lat">纬度</param>
/// <param name="lng">经度</param>
/// <returns>城市名称</returns>
public static string GetCity(string lat, string lng)
{
string url = string.Format(
"{0}?output={1}&ak={2}&location={3},{4}",
ConfigurationManager.AppSettings["BaiduGeocodingApi"],
"json",
ConfigurationManager.AppSettings["BaiduAK"],
lat,
lng);
string cityString = RemoteQuery.GetResponse(url);
if (string.IsNullOrEmpty(cityString)) return string.Empty;
JObject city = (JObject)JsonConvert.DeserializeObject(cityString);
if (city["status"].ToString() != "0")
{
log.Error("Get city error with status: " + city["status"]);
return string.Empty;
}
return (string)city["result"]["addressComponent"]["city"];
}
public static string GetResponse(string accessUrl)
{
string response = string.Empty;
try
{
#region 访问服务url,并获取返回的json数据
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(accessUrl);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
HttpWebResponse httpWebResponse = null;
httpWebResponse = request.GetResponse() as HttpWebResponse;
StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
response = sr.ReadToEnd();
sr.Close();
#endregion
}
catch (Exception ex)
{
log.Info("Error when accessing: " + accessUrl);
log.Error(ex.Message);
}
return response;
}
}
<!--配置文件weather longitude=116.31985&latitude=39.959836 北京市-->
<add key="BaiduWeatherApi" value="http://api.map.baidu.com/telematics/v3/weather" />
<add key="BaiduAK" value="http://www.mamicode.com/3lX7GmQLza5KzQWde4ZIzMul" />
C#模拟http 发送post或get请求