我要打電話與POST參數的API,例如:如何調用XML POST API
- URL = http://localhost/myAPI/
- ARGS =選項=藍色&類型=車
我看過XDocument,但不知道如何在請求中發送參數。我也不確定我會如何異步調用,即使我應該或者如果它更好/更容易在另一個線程中運行。
我會從我基於Windows的C#應用程序調用此。
我要打電話與POST參數的API,例如:如何調用XML POST API
我看過XDocument,但不知道如何在請求中發送參數。我也不確定我會如何異步調用,即使我應該或者如果它更好/更容易在另一個線程中運行。
我會從我基於Windows的C#應用程序調用此。
您可以使用的Upload methods之一。
WebClient client = new WebClient();
string response = client.UploadString(
"http://localhost/myAPI/?options=blue&type=car",
"POST data");
從哪裏調用它? JavaScript的?如果是這樣你可以使用jQuery:
http://api.jquery.com/jQuery.post/
$.post('http://localhost/myAPI/', { options: "blue", type="car"}, function(data) {
$('.result').html(data);
});
數據將包含您的文章的結果。
如果從服務器端你可以使用HttpWebRequest並用你的params寫入它的流。
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://localhost/myAPI/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "options=blue&type=car";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
來自問題:'我會從我基於Windows的C#應用程序調用這個.' – 2012-04-09 17:39:02
要扔另一種選擇成環,你可能要考慮使用的HttpClient
的PostAsync
方法在.NET 4.5。一個公認的未經測試的刺:
HttpClient client = new HttpClient();
var task = client.PostAsync(string.Format("{0}{1}", "http://localhost/myAPI", "?options=blue&type=car"), null);
Car car = task.ContinueWith(
t =>
{
return t.Result.Content.ReadAsAsync<Car>();
}).Unwrap().Result;
感謝您的指針,這有助於很多。我也發現我需要設置client.Headers。Headers [「Content-Type」] =「application/x-www-form-urlencoded」; – Drahcir 2012-04-09 20:24:41