C#HttpWebRequest/Response给出400个错误请求。但不适用于Firefox HTTP资源测试
我需要使用xml数据发出POST请求C#HttpWebRequest/Response给出400个错误请求。但不适用于Firefox HTTP资源测试,c#,post,httpwebrequest,http-post,httpwebresponse,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 = "";
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());
}
}
}
及
它总是给我一个HttpCliendException
:
video_api.HttpClientException: HttpClient exception :HTTP response error. with `code: 400` and `status: Bad Request`
但是当我用Firefox插件HTTP资源测试
尝试它时,它运行良好,并使用相同的XML文档获得了202接受状态
我对内容类型和数据进行了处理。在调用post请求之前,内容类型是text/xml,而
数据。length
是143
我知道一些网站对请求头很挑剔,只根据这些值返回不同的结果。比较FireFox中HTTP请求的请求头和您的请求,如果您模拟FireFox资源测试中的头,它很可能会工作(request.AddHeader(“name”、“value”)
)。另一个需要注意的区别可能是用户代理,它同样可能对web服务器挑剔。使用fiddler(http://www.fiddler2.com/fiddler2/)查看Firefox发送的确切标题。然后查看您发送的标题的不同之处。在我的项目中,我在config.area中使用了一些自定义设置
<defaultProxy useDefaultCredentials="true">
...
</defaultProxy>
另一个解决方案是将SSL和非SSL端口弄乱
当您将纯http连接到https端口时,Apache上的应答400错误请求。您可能需要一个
用户代理。
<defaultProxy useDefaultCredentials="true">
...
</defaultProxy>
request.Proxy = null;