使用WebClient使用htaccess向Apache服务器发送POST请求

时间:2013-12-04 05:11:33

标签: c# php post webclient

我在使用WebClient使用htaccess向apache服务器发送POST请求时遇到了问题(我尝试使用HttpRequest以及WebRequest,但结果相同)。 我在PHP上有来自供应商的以下示例:

$soap = curl_init(url);
curl_setopt($soap, CURLOPT_POST, 1);
curl_setopt($soap, CURLOPT_RETURNTRANSFER, 1);
$XML = file_get_contents("test.xml");
$request = <<<XML
$XML
XML;
curl_setopt($soap, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($request)));
curl_setopt($soap, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($soap);
curl_close($soap);

我在C#上的版本是:

public static string Post(string login, string password, string url, string content) {
    var result = String.Empty;
    var uri = new Uri(url);

    using (var client = new WebClient()) {
        client.Credentials = new NetworkCredential(login, password);

        client.Encoding = Encoding.UTF8;
        client.Headers[HttpRequestHeader.ContentType] = "text/xml; charset=UTF-8";
        client.Headers[HttpRequestHeader.Accept] = "application/xml";
        result = client.UploadString(uri, content);
    }

    return result;
}

当我运行程序时,我遇到400错误(错误请求)的异常。我使用Fiddler2嗅探请求并发现以下错误消息:“请求标题字段丢失”:'分隔符 任何人都可以帮我找到请求中的错误以及服务器拒绝请求的原因吗?

P.S:请求标题

POST http://production.is.topdelivery.ru/tests/xmlGate/index.php HTTP/1.1
Content-Type: text/xml; charset=utf-8
Authorization: Basic YmFiYWR1OmJhYmFkdXBhc3M=
Host: production.is.topdelivery.ru
Content-Length: 1617
Expect: 100-continue

2 个答案:

答案 0 :(得分:0)

在我的情况下,以下代码正常运行

private string post(string content)
{
    var result = String.Empty;
    var uri = new Uri(_url);

    WebRequest req = HttpWebRequest.Create(uri);
    req.Method = "POST";
    req.ContentType = "text/xml";

    String encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:pass"));
    req.Headers.Add("Authorization", "Basic " + encoded);

    using (var s = req.GetRequestStream())
    using (var sw = new StreamWriter(s, Encoding.UTF8))
    {
        sw.Write(content);
    }
    using (var s = req.GetResponse().GetResponseStream())
    using (var sr = new StreamReader(s, Encoding.UTF8))
    {
        result = sr.ReadToEnd();
    };
    return result;
}

答案 1 :(得分:0)

这对我有帮助。即使旧版本没有问题,我也遇到了新版Apache没有看到凭据的问题。我改变了

client.Credentials = new NetworkCredential(login, password);

String encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:pass"));
    req.Headers.Add("Authorization", "Basic " + encoded);

它有效!

谢谢。