ASP.NET post访问外网接口获取数据

 

方法一:

 string postData = string.Format("a=1&b=2");   //post传递参数
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.Default;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求
       
            // 设置参数
            request = WebRequest.Create("http://www.baidu.com") as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码
           string a= sr.ReadToEnd();
           Response.Write(a.ToString());

 

 

 

方法二:string file="www.baidu.com";

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
        string a = sr.ReadToEnd();

Response.Write(a.ToString());

相关文章
相关标签/搜索