C#模拟浏览器发get,post请求

调用:            
        JArray ja = (JArray)JsonConvert.DeserializeObject("["+GetDataPost()+"]");
            Response.Write(ja[0]["tinyurl"]);


//get方式 
private string GetData(string req)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string responseBody = stream.ReadToEnd();
            stream.Close();
            response.Close();
            return responseBody;
        }

//Post方式
        private string GetDataPost()
        {
            string strURL = "http://dwz.cn/create.php";
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strURL);
            //Post请求方式
            request.Method = "POST";
            // 内容类型
            request.ContentType = "application/x-www-form-urlencoded";

            //这是原始代码:
            string paraUrlCoded = "url=http://www.jd.com/";
            byte[] payload;
            //将URL编码后的字符串转化为字节
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的 ContentLength 
            request.ContentLength = payload.Length;
            //获得请 求流
            Stream writer = request.GetRequestStream();
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            // 关闭请求流
            writer.Close();
            System.Net.HttpWebResponse response;
            // 获得响应流
            response = (System.Net.HttpWebResponse)request.GetResponse();
            StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string responseBody = stream.ReadToEnd();
            stream.Close();
            response.Close();
            return responseBody;
        }

 

你可能感兴趣的:(C#模拟浏览器发get,post请求)