【发布时间】:2015-03-05 15:54:32
【问题描述】:
我正在尝试使用 API,但 GET 和 POST 没有任何问题,但 PUT 不起作用。我尝试了很多不同的示例,最后偶然发现等待超过 5 秒(5000 毫秒不工作,5100 毫秒不工作)它开始正常工作。但为什么会这样?我怎样才能避免这种情况?每次注册表更新需要 5 秒的等待时间,我真的不明白为什么 POST 无需等待就能正常工作,而 PUT 需要 5 秒才能工作。
在这里,我将我使用的方法与Thread.Sleep(5100) 放在一起。正如我所说,当我制作WebResponse response = request.GetResponse(); 时没有这条线会给我一个错误。
public void call(string url, object jsonObj)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(urlSplio);
// Create POST data and convert it to a byte array.
request.Method = "PUT";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["User"], "WebConfigurationManager.AppSettings["Key"]");
string json = JsonConvert.SerializeObject(jsonObj);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// 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();
Thread.Sleep(5100);
// 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.
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
【问题讨论】:
标签: c# .net visual-studio-2013 httpwebrequest httpwebresponse