C#中用HttpWebRequest/HttpWebResponse来发送/接收数据

 

//获取方法httPost请求URL发送过来的数据

public ActionResult ToUrl()
        {
            string result = "";
            string jsonStr = "", line;
            try
            {

                Stream streamResponse = Request.InputStream;
                StreamReader streamRead = new StreamReader(streamResponse, Encoding.Default);

                while ((line = streamRead.ReadLine()) != null)
                {
                    jsonStr += line;
                }
                streamResponse.Close();
                streamRead.Close();

                result = jsonStr;
            }
            catch (Exception ex)
            {
                result = "msg-数据发布(In)异常:" + ex.Message;
            }
            return Content(jsonStr);

        }

/*向网页发送数据并接收返回信息:
  假设URL为:
http://locahost/home/ToUrl   (请求方法:ToUrl)
*/
private string httpPost(string URL, string Parameters)
{
    byte[] bytes = Encoding.Default.GetBytes(Parameters);
 
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
    req.Proxy = new WebProxy(ProxyString, true);
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8) Gecko/20051111 Firefox/1.5";
    req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html";
    req.KeepAlive = true;
    req.Referer = string.Format("
https://www.XXX.com/"; //修改为自己的referer
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";
 
    req.ContentLength = bytes.Length;
    Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length); //Push it out there
    os.Close();
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    if (resp == null) return null;
    StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
    string sReturn = sr.ReadToEnd().Trim();
    resp.Close(); sr.Close();
    return sReturn;
}

//接收网页数据
private string httpGet(string URL)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
    //req.Proxy = new WebProxy(ProxyString, true); //true means no proxy
    WebResponse resp = req.GetResponse();
    StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default);
    string sReturn = sr.ReadToEnd().Trim();
    resp.Close(); sr.Close();
    return sReturn;
}

 

 

来源于:www.hackbadboy.com B.B.S.T信息安全团队


原文链接: http://blog.csdn.net/mypc2010/article/details/7070554

你可能感兴趣的:(C#中用HttpWebRequest/HttpWebResponse来发送/接收数据)