在外部域上提交表单(C#或Javascript)

时间:2015-09-15 08:00:45

标签: javascript c# jquery ajax forms

我需要一种方法来自动填写并提交表单。它必须从URL开始,因为我需要从我的domoticz中调用它。我尝试使用AJAX提交并注入javascript,但我得到了同源策略。我尝试提交的表单不是我的,所以我无法对此进行更改。

我试过了:

JQUERY

setTimeout(function(){ $("#frame").attr("src", ":javascript:alert('test');"); }, 3000);

C#

frame.Src = "https://URL"; int milliseconds = 10000; Thread.Sleep(milliseconds); frame.Src = "javascript:alert('test');";

C#2

`

    WebRequest req = WebRequest.Create("URL");
    string postData = "field1=11111&field2=22222&field3=33333";
    byte[] send = Encoding.Default.GetBytes(postData);
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    req.ContentLength = send.Length;
    Stream sout = req.GetRequestStream();
    sout.Write(send, 0, send.Length);
    sout.Flush();`

为什么我要用这个?通过表格,您可以在车上办理一小时。一小时后你必须再次检查。我整天忘记了一整天。

1 个答案:

答案 0 :(得分:1)

我建议你使用以下课程:

public static class WebRequester
{
    /// <summary>
    /// Sending POST request.
    /// </summary>
    /// <param name="url">Request Url.</param>
    /// <param name="data">Data for request.</param>
    /// <param name="userName">user name for log in</param>
    /// <param name="password">password for log in</param>
    /// <returns>Response body.</returns>
    public static string HttpPost(string url, string data, string userName = "", string password = "", int timeout = 100000)
    {

        string Out = String.Empty;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        try
        {
            req.ContentType = "application/json";
            req.Method = "POST";
            req.ProtocolVersion = HttpVersion.Version11;
            req.Accept = "*/*";

            AddAuthentication(userName, password, req);

            req.Timeout = timeout;
            //req.ContentType = "application/x-www-form-urlencoded";
            byte[] sentData = Encoding.UTF8.GetBytes(data);
            req.ContentLength = sentData.Length;
            using (System.IO.Stream sendStream = req.GetRequestStream())
            {
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Flush();
                sendStream.Close();
            }
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            System.IO.Stream ReceiveStream = res.GetResponseStream();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
            {
                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (ArgumentException ex)
        {
            Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        return Out;
    }

    /// <summary>
    /// Sending GET request.
    /// </summary>
    /// <param name="url">Request Url.</param>
    /// <param name="data">Data for request.</param>
    /// <param name="userName">user name for log in</param>
    /// <param name="password">password for log in</param>
    /// <returns>Response body.</returns>
    public static string HttpGet(string url, string data, string userName, string password)
    {
        string Out = String.Empty;
        Uri uri = new Uri(url);

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + (string.IsNullOrEmpty(data) ? "" : "?" + data));
        req.ContentType = "application/json";
        req.Method = "GET";

        AddAuthentication(userName, password, req);
        try
        {
            System.Net.WebResponse resp = req.GetResponse();
            using (System.IO.Stream stream = resp.GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
                {
                    Out = sr.ReadToEnd();
                    sr.Close();
                }
            }
        }
        catch (ArgumentException ex)
        {
            Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        return Out;
    }

    private static void AddAuthentication(string userName, string password, HttpWebRequest req)
    {
        if (userName != null && password != null)
        {
            string base64Credentials = GetEncodedCredentials(userName, password);
            req.Headers.Add("Authorization", "Basic " + base64Credentials);
        }
    }

    /// <summary>
    /// Sending Delete request.
    /// </summary>
    /// <param name="url">Request Url.</param>
    /// <param name="data">Data for delete.</param>
    /// <param name="userName">user name for log in</param>
    /// <param name="password">password for log in</param>
    /// <returns>Response body.</returns>
    public static string HttpDelete(string url, string data, string userName, string password)
    {
        string Out = String.Empty;
        Uri uri = new Uri(url);

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url + (string.IsNullOrEmpty(data) ? "" : "?" + data));
        req.ContentType = "application/json";
        req.Method = "DELETE";

        AddAuthentication(userName, password, req);

        try
        {
            System.Net.WebResponse resp = req.GetResponse();
            using (System.IO.Stream stream = resp.GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
                {
                    Out = sr.ReadToEnd();
                    sr.Close();
                }
            }
        }
        catch (ArgumentException ex)
        {
            Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        return Out;
    }

    private static string GetEncodedCredentials(string userName, string password)
    {
        string mergedCredentials = string.Format("{0}:{1}", userName, password);
        byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
        return Convert.ToBase64String(byteCredentials);
    }
}

您可以按以下方式使用它将数据发布到Web服务器:

var result = WebRequester.HttpPost(url, jsonData, userName, password);

结果将包含来自服务器的答案。