• 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信息安全团队

  • 相关阅读:
    定时器的使用
    new LayoutParams 使用
    判断,日期是是昨天,前天 ,今天
    google推出的SwipeRefreshLayout下拉刷新用法
    Intent的Flag
    Eclipse Java注释模板设置详解
    Eclipse的模板设置代码
    Android如何在java代码中设置margin
    软键盘挡住输入框的解决方案
    Android自定义遮罩层设计
  • 原文地址:https://www.cnblogs.com/secbook/p/2654911.html
Copyright © 2020-2023  润新知