【问题标题】:Invalid URI when calling HTTPWebRequest调用 HTTPWebRequest 时 URI 无效
【发布时间】:2013-06-14 22:20:43
【问题描述】:

我编写了一个控制台应用程序,它调用一个 RESTful Web 服务,通过 HTTP 发送 XML 请求,该请求返回 XML 响应。这是我目前正在使用的代码:

WebRequest wrq = WebRequest.Create("<?xml version=1.0 encoding=ISO-8859-1?>
<Request xmlns=https://sapiqa.overstock.com/api><MerchantKey>"+MerchantKey+"
</MerchantKey><AthenticationKey>"+AuthenticationKey+"</AuthenticationKey><"+APIMethod+"
/></Request>");
wrq.Method = "POST";
// Create POST data and convert it to a byte array. Strip out unnecessary text. 
byte[] byteArray = Encoding.UTF8.GetBytes(URL.Replace(APIMethod, ""));
// Set the ContentType property of the WebRequest. 
wrq.ContentType = "text/xml";
// Set the ContentLength property of the WebRequest. 
wrq.ContentLength = byteArray.Length;

Stream dataStream = wrq.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 = wrq.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. 
GetOrders2Response = responseFromServer;
Console.WriteLine(responseFromServer);

// Clean up the streams. 
reader.Close();
dataStream.Close();
response.Close();
Console.ReadKey();

当我运行此代码时,我收到错误说明:

Invalid URI: The URI scheme is not valid.

如何通过 WebRequest 进行补救,以发送格式正确的 XML 并接收 XML 响应?

【问题讨论】:

  • 发出 POST 请求需要更多的工作。见stackoverflow.com/q/2550965/56778。或者搜索 [httpwebrequest post]。
  • @JimMischel 您能否在答案中进一步详细说明?
  • msdn.microsoft.com/en-us/library/debx8sh9.aspx的例子很详细。确实有数百个例子。在httpwebrequest post example 上进行简单的 Google 搜索将为您提供大量样本供您选择。
  • @JimMischel 感谢您提供此链接。我仍然不清楚如何将 MerchantKey 和 AuthenticationKey 值作为 POST 请求的一部分发送?
  • 我也不知道如何使用那个 REST API。我们已经向您展示了如何发出 POST 请求。由您决定如何格式化有效负载(您的数据),以便服务器接受它。也许您可以找到该 API 调用的一些文档。

标签: c# xml httpwebrequest


【解决方案1】:

正如错误和文档明确所述,WebRequest.Create 采用 URL,而不是 POST 负载。

您需要将 URL 传递给 Create(),并将 XML 负载写入请求流。

【讨论】:

  • 那么,我该如何构建您提到的 XML 有效负载?如果 Crete 方法采用简单 URL,我如何传入 MerchantKey 和 AuthenticationKey 变量值?
  • @SidC - 看看上面 Jim Mischel 链接的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多