我需要用xml數據發出POST請求。C#HttpWebRequest/Response給出了400個錯誤的請求。但不是Firefox的HTTP資源測試
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
試了一下,它運行得很好,並得到202 Accepted status
用相同的XML文檔。
在調用post請求之前,我安慰了內容類型和data.length,內容類型是text/xml,data.length
是143
。
您可能需要一個'User-Agent'。 – SLaks