是否可以将数据从C#应用程序发送到网站/网络服务器?

时间:2010-12-17 21:21:00

标签: c# php apache http post

我希望有人可以帮我解决一直困扰我多年的问题。

是否可以在打开浏览器时将数据从C#应用程序发送到网页,例如如果你有一个在线登录表,并希望从你的C#应用​​程序发布该表单的用户名和密码。

我看到类似于打开浏览器到表单页面的内容,并将登录详细信息从程序发布到该页面,然后页面可以立即处理表单,从而登录并将它们发送到主页。这可能吗?

提前致谢

3 个答案:

答案 0 :(得分:9)

是肯定的。

您可以使用HttpWebRequest与网页或Web服务器(或Web服务)进行通信。这是我用来从facebook url获取数据的实际代码:

internal static string FbFetch(string url)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var responseText = reader.ReadToEnd();
            return responseText;
        }
    }
}

但是,您所描述的内容称为“HTML屏幕抓取”,它可能是构建应用程序的繁琐而脆弱的方法。单调乏味,因为很难在所有UI糖果中徘徊,而且很脆弱,因为如果页面设计师改变了他的页面,你的屏幕抓取将不再有效。

祝你好运。

答案 1 :(得分:1)

要回答关于HTTP帖子(带附件)的问题,由于附件,它更加难以理解。这是我用来将图像发布到FaceBook的实际代码。

    /// <summary>
    /// Create a new HttpWebRequest with the default properties for HTTP POSTS
    /// </summary>
    /// <param name="url">The URL to be posted to</param>
    /// <param name="referer">The refer</param>
    /// <param name="cookies">CookieContainer that should be used in this request</param>
    /// <param name="postData">The post data</param>
    private string CreateHttpWebUploadRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData, FileInfo fileData, string fileContentType)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);

        // set the request variables
        request.Method = WebRequestMethods.Http.Post;
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.CookieContainer = cookies;
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4";
        request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*";
        request.Headers.Add("Accept-Encoding: gzip,deflate");
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        request.Headers.Add("Accept-Language: en-us");
        request.Referer = referer;
        request.KeepAlive = true;
        request.AllowAutoRedirect = false;

        // process through the fields
        StringBuilder sbHeader = new StringBuilder();

        // add form fields, if any
        if (postData != null)
        {
            foreach (string key in postData.AllKeys)
            {
                string[] values = postData.GetValues(key);
                if (values != null) 
                {
                    foreach (string value in values)
                    {
                        if (!string.IsNullOrEmpty(value))
                            sbHeader.AppendFormat("--{0}\r\n", boundary);
                            sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n", key, value);
                    }
                }
            }
        }

        if (fileData != null)
        {
            sbHeader.AppendFormat("--{0}\r\n", boundary);
            sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "media", fileData.Name);
            sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", fileContentType);
        }

        byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
        byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
        long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;

        // set content length
        request.ContentLength = contentLength;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(header, 0, header.Length);

            // write the uploaded file
            if (fileData != null)
            {
                // write the file data, if any
                byte[] buffer = new Byte[fileData.Length];
                var bytesRead = fileData.OpenRead().Read(buffer, 0, (int)(fileData.Length));
                requestStream.Write(buffer, 0, bytesRead);
            }

            // write footer
            requestStream.Write(footer, 0, footer.Length);
            requestStream.Flush();
            requestStream.Close();

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    return stIn.ReadToEnd();
                }
            }
        }
    }

<强>更新 为了使其完整,这里是帖子的代码,而不需要文件附件。我再次使用此代码发布到FaceBook。

    /// <summary>
    /// Create a new HttpWebRequest with the default properties for HTTP POSTS
    /// </summary>
    /// <param name="url">The URL to be posted to</param>
    /// <param name="referer">The refer</param>
    /// <param name="cookies">CookieContainer that should be used in this request</param>
    /// <param name="postData">The post data (needs to be formatted in name=value& format</param>
    private string CreateHttpWebPostRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData)
    {
        var sbPostData = new StringBuilder();

        if (postData != null)
        {
            foreach (string key in postData.AllKeys)
            {
                string[] values = postData.GetValues(key);
                if (values != null)
                {
                    foreach (string value in values)
                    {
                        if (!string.IsNullOrEmpty(value))
                            sbPostData.Append(string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
                    }
                }
            }
        }

        var parameterString = Encoding.UTF8.GetBytes(sbPostData.ToString());
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;
        request.CookieContainer = cookies;
        request.ContentLength = parameterString.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4";
        request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*";
        request.Headers.Add("Accept-Encoding: gzip,deflate");
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        request.Headers.Add("Accept-Language: en-us");
        request.Referer = referer;
        request.KeepAlive = true;
        request.AllowAutoRedirect = false;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(parameterString, 0, parameterString.Length);
            requestStream.Close();

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    return stIn.ReadToEnd();
                }
            }
        }
    }  

答案 2 :(得分:0)

您可以直接在C#中自动执行webbrowser control。与HttpWebRequest不同,这适用于任何网站。

但如果您有更多的钱而不是时间,请考虑使用商业广告component