https在C#窗体中发布

时间:2016-01-11 12:36:57

标签: c# https

我需要你的帮助。我必须调用post方法到https服务器,我有一些问题。就像那样:

用于检查网址我在Firefox扩展程序中使用restclient。它起作用并做出回应。但是当我在C#Win形式中使用相同的参数时,它不起作用。换句话说:

public static string StartReguest(string header ,string headerVal,string data )
{
            byte[] byteArray = Encoding.UTF8.GetBytes(data);  
            HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
            request.Headers.Add("Accept-Language", "ru");
            request.Headers.Set(header, headerVal);
            request.Credentials = CredentialCache.DefaultCredentials;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Method = "POST";
            request.ContentLength = byteArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            **Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Flush();
            dataStream.Close();**


           request.Accept = "text/html,application/xhtml+xml/application/xml; q=0.9,'/';q=0.8";
            request.KeepAlive = true;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            reader.ReadLine();
            string html = reader.ReadToEnd();
            return html;
}

问题在于粗体,实际上这不是问题我没有得到错误。程序有效。但它不会发布我写的任何文字。起初我想说uri是在https中,但它在http中工作,这就是为什么我不认为问题与证书有关。 我猜数据流无法写入数据。但为什么 ?

2 个答案:

答案 0 :(得分:0)

尝试使用:

            var streamWriter = new StreamWriter(request.GetRequestStream());

            streamWriter.Write(byteArray, 0, byteArray.Length);
            streamWriter.Flush();
            streamWriter.Close();

而不是:

        **Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Flush();
        dataStream.Close();**

答案 1 :(得分:0)

嗯,我有点担心参数是如何传递的。

您如何看待使用带有UrlEncode的List或Dictionary传递参数?

例如,你可以这样做:

Dictionary<string,string> postParams表示字符串参数。

string strData = "";

foreach (string key in postParams.Keys)
    {
        strData += HttpUtility.UrlEncode(key) + "="
              + HttpUtility.UrlEncode(postParameters[key]) + "&";
    }

byte[] data = Encoding.ASCII.GetBytes(strData);

这适用于WinForms非常好!

我希望有所帮助!