xmlデータでPOSTリクエストを行う必要があります。C#HttpWebRequest/Responseは400 Bad Requestを返します。 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());
}
}
}
それはいつも私にを与える:
video_api.HttpClientException: HttpClient exception :HTTP response error. with `code: 400` and `status: Bad Request`
しかし、私はFirefoxのアドオンHTTP Resource Test
でそれをしようとしたとき、それが正常に走り、同じXMLドキュメントで202 Accepted status
を取得します。
投稿要求が呼び出される前にcontent-typeとdata.lengthを執筆しました。コンテンツタイプはtext/xmlで、data.length
は143
です。
おそらく 'User-Agent'が必要です。 – SLaks