C#HttpWebRequest / Response提供400 Bad Request。但不是Firefox HTTP资源测试

时间:2011-09-13 01:29:03

标签: c# post httpwebrequest http-post httpwebresponse

我需要使用xml数据发出POST请求。

String xml = "";
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
HttpClient.post(url, data, "text/xml")

然后我调用POST函数:

public static String post(String url, byte[] data, String contentType){
        String body = "";
        body = getResponse("POST", url, data, contentType, 80);
        return body;
    }

现在我调用此函数来发出请求/获取响应:

public static String getResponse(String method, String url, byte[] data, String contentType, int serverPort)
    {
        String result = null;
        HttpWebRequest request = sendRequest(method, url, data, contentType, serverPort);
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
            if (response != null){
                // Get the stream associated with the response
                Stream receiveStream = response.GetResponseStream ();
                // Pipes the stream to a higher level stream reader
                StreamReader readStream = new StreamReader (receiveStream, System.Text.Encoding.UTF8);
                result = readStream.ReadToEnd ();
            }
        }
        catch(WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError){
                throw new HttpClientException("HTTP response error. ", (int)(((HttpWebResponse)ex.Response).StatusCode), ((HttpWebResponse)ex.Response).StatusDescription);
            }
            else{
                throw new HttpClientException("HTTP response error with status: " + ex.Status.ToString());
            }
        }
}

public static HttpWebRequest sendRequest(String method, String url, byte[] data, String contentType, int serverPort){
        HttpWebRequest request = null;
        try
        {
            UriBuilder requestUri = new UriBuilder(url);
            requestUri.Port = serverPort;
            request = (HttpWebRequest)WebRequest.Create(requestUri.Uri);
            request.Method = method;
            //
            if ((method == "POST") && (data != null) && (data.Length > 0)){
                request.ContentLength = data.Length;
                request.ContentType = ((String.IsNullOrEmpty(contentType))?"application/x-www-form-urlencoded":contentType);
                Stream dataStream = request.GetRequestStream ();
                dataStream.Write (data, 0, data.Length);
                // Close the Stream object.
                dataStream.Close ();
            }
        }
        catch(WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError){
                throw new HttpClientException("HTTP request error. ", (int)(((HttpWebResponse)ex.Response).StatusCode), ((HttpWebResponse)ex.Response).StatusDescription);
            }
            else{
                throw new HttpClientException("HTTP request error with status: " + ex.Status.ToString());
            }
        }
}

总是给我一个HttpCliendException

video_api.HttpClientException: HttpClient exception :HTTP response error.  with `code: 400` and `status: Bad Request`

但是当我尝试使用Firefox插件HTTP Resource Test时,它运行正常,并使用相同的XML文档获取202 Accepted status

在调用post请求之前,我安排了content-type和data.length,内容类型是text / xml,data.length143

4 个答案:

答案 0 :(得分:2)

使用fiddler(http://www.fiddler2.com/fiddler2/)查看Firefox发送的标题。然后看看你发送的标题有什么不同。

答案 1 :(得分:1)

我知道一些网站对请求标题很挑剔,并且仅根据这些值返回不同的结果。比较FireFox中HTTP请求的请求标头和您的请求,如果您模仿FireFox资源测试中的标头,它很可能会起作用(Request.AddHeader("name", "value"))。需要注意的另一个区别可能是用户代理,这对于Web服务器来说也是挑剔的。

答案 2 :(得分:0)

在我的项目中,我在config.area中使用了一些自定义设置

    <defaultProxy useDefaultCredentials="true">
...
    </defaultProxy>

它帮助我禁用了代理:

request.Proxy = null;

答案 3 :(得分:0)

另一种解决方案是,它会搞乱SSL和非SSL端口。

当您将简单的HTTP与https端口进行对话时,答案是对Apache的错误请求。