发送参数HttpWebRequest返回XML

时间:2017-10-27 09:00:24

标签: c# post parameters send httpwebresponse

早上好,

我正在尝试连接到支付网关,该网关使用HttpWebRequest向您发送帖子参数。

在api中完成的代码是php,但我需要在C#中。

function send_trans($url, $postData) {
$headers = array( 'Connection: Keep-Alive',
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko
/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 40); // timeout en 40 segundos
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$xml = curl_exec($ch);
curl_close($ch);
return ($xml);
}

使用以下代码尝试过它。

public static string HttpPostRequest (string url, Dictionary <string, string> postParameters)
        {
            string postData = "";

            foreach (string key in postParameters.Keys)
            {
                postData + = key + "=" + postParameters [key] + "&";
            }

            HttpWebRequest myHttpWebRequest = (HttpWebRequest) HttpWebRequest.Create (url);
            myHttpWebRequest.Method = "POST";

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

            myHttpWebRequest.ContentType = "application / x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = data.Length;

            Stream requestStream = myHttpWebRequest.GetRequestStream ();
            requestStream.Write (data, 0, data.Length);
            requestStream.Close ();

            HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse ();

            Stream responseStream = myHttpWebResponse.GetResponseStream ();

            StreamReader myStreamReader = new StreamReader (responseStream, Encoding.Default);

            string pageContent = myStreamReader.ReadToEnd ();

            myStreamReader.Close ();
            responseStream.Close ();

            myHttpWebResponse.Close ();

            return pageContent;
        }

它给我的错误是在Stream responseStream = myHttpWebResponse.GetResponseStream()的行中,我尝试过其他代码,它在GetResponseStream中始终是相同的错误。

0 个答案:

没有答案