我遇到以下问题 - 我尝试从具有.NET CF 3.5
的设备向AWS IoT执行POST请求,以将消息发布到主题。它适用于对Azure IoT Hub和.NET 4.5
上的应用程序执行相同操作。但是当我尝试向AWS发出请求时,我总是得到异常the connection has timed out
。
这就是我执行请求的方式:
public static HttpWebResponse InvokeHttpRequest(Uri endpointUri,
string httpMethod,
IDictionary<string, string> headers,
string requestBody)
{
try
{
var request = ConstructWebRequest(endpointUri, httpMethod, headers);
if (!string.IsNullOrEmpty(requestBody))
{
var buffer = new byte[requestBody.Length]; // arbitrary buffer size
var requestStream = request.GetRequestStream();
using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
{
var bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
requestStream.Flush();
requestStream.Close();
}
return CheckResponse(request);
}
catch (WebException ex)
{
using (var response = ex.Response as HttpWebResponse)
{
if (response != null)
{
var errorMsg = ReadResponseBody(response);
Console.WriteLine("\n-- HTTP call failed with exception '{0}', status code '{1}'", errorMsg, response.StatusCode);
}
return null;
}
}
}
网址,标题和其他所有内容都可以,因为它适用于.NET 4.5。是否存在可能导致此类问题的CF的已知限制?
注意 我需要添加
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true"/>
</settings>
在.NET 4.5客户端中,因为否则我得到了异常The server committed a protocol violation. Section=ResponseStatusLine
,所以这个信息可能有所帮助。谢谢!
UPD
以下是ConstructWebRequest
和CheckResponse
代码:
public static HttpWebRequest ConstructWebRequest(Uri endpointUri,
string httpMethod,
IDictionary<string, string> headers)
{
var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Method = httpMethod;
foreach (var header in headers.Keys)
{
// not all headers can be set via the dictionary
if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
continue;
else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
request.ContentLength = long.Parse(headers[header]);
else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
request.ContentType = headers[header];
else
request.Headers.Add(header, headers[header]);
}
return request;
}
public static void CheckResponse(HttpWebRequest request)
{
// Get the response and read any body into a string, then display.
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("\n-- HTTP call succeeded");
var responseBody = ReadResponseBody(response);
if (!string.IsNullOrEmpty(responseBody))
{
Console.WriteLine("\n-- Response body:");
Console.WriteLine(responseBody);
}
}
else
Console.WriteLine("\n-- HTTP call failed, status code: {0}", response.StatusCode);
}
}