? 1.get方法调用接口获取json文件内容? ??
public?void?GetFunction()
????????{
????????????string?serviceAddress?=?"http://222.111.999.444:8687/tttr/usercrd/12/b7e50cb45a?userid=9999";
????????????HttpWebRequest?request?=?(HttpWebRequest)WebRequest.Create(serviceAddress);
????????????request.Method?=?"GET";
????????????request.ContentType?=?"text/html;charset=UTF-8";
????????????HttpWebResponse?response?=?(HttpWebResponse)request.GetResponse();
????????????Stream?myResponseStream?=?response.GetResponseStream();
????????????StreamReader?myStreamReader?=?new?StreamReader(myResponseStream,?Encoding.UTF8);
????????????string?retString?=?myStreamReader.ReadToEnd();
????????????myStreamReader.Close();
????????????myResponseStream.Close();
????????????Response.Write(retString);
????????}
? ? ??? 2.post方法调用接口获取json文件内容
public void PostFunction()
{
string serviceAddress = "http://222.111.999.444:8687/tttr/usercrd/uuu/12/dfd7e4";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}";
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
//解析josn
JObject jo = JObject.Parse(retString);
Response.Write(jo["message"]["mmmm"].ToString());
}
3.其他方式
/// <summary>
/// POST请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="data">请求内容</param>
/// <returns></returns>
public string Post(string data, string url)
{
//先根据用户请求的uri构造请求地址
string serviceUrl = url;
//创建Web访问对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//把用户传过来的数据转成“UTF-8”的字节流
byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
myRequest.Method = "POST";
myRequest.ContentLength = buf.Length;
myRequest.ContentType = "application/json";
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect = true;
//发送请求
Stream stream = myRequest.GetRequestStream();
stream.Write(buf, 0, buf.Length);
stream.Close();
//获取接口返回值
//通过Web访问对象获取响应内容
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
//通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
reader.Close();
myResponse.Close();
return returnXml;
}
|