方法一
http://blog.csdn.net/angle_greensky110/article/details/52209497
protected string GetJson(string url)
{
//访问https需加上这句话
// ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
//访问http(不需要加上面那句话)
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Encoding = Encoding.UTF8;
string returnText = wc.DownloadString(url); if (returnText.Contains("errcode"))
{
//可能发生错误
}
//Response.Write(returnText);
return returnText;
}
方法二 (webservice)
/// <summary>
/// 通过Post方式获取数据
/// </summary>
/// <param name="url"></param>
/// <param name="data">可为空</param>
/// <returns></returns>
public string DoPost(string url, string data)
{
HttpWebRequest req = GetWebRequest(url, "POST");
byte[] postData = Encoding.UTF8.GetBytes(data);
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
} public HttpWebRequest GetWebRequest(string url, string method)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
req.ContentType = "text/json";
req.Method = method;
req.KeepAlive = true;
req.UserAgent = "guanyisoft";
req.Timeout = 1000000;
req.Proxy = null;
return req;
} public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
// 每次读取不大于256个字符,并写入字符串
char[] buffer = new char[256];
int readBytes = 0;
while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
{
result.Append(buffer, 0, readBytes);
}
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
} return result.ToString();
}