1
// string url = "http://localhost:19315/test/postWithParamters?param1=1&param2=2";
string url = "http://m.mydomain.com/1.0/services/logException?p1=WindowsPhone&p2=a&p3=b&p4=2012-05-01T14:57:32.8375298-04:00&p5=someuser&p6=test&p7=info&p8=data";

WebClient postWithParamsClient = new WebClient();
postWithParamsClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);

Uri address = new Uri(url, UriKind.Absolute);
postWithParamsClient.Headers["Content-Length"] = url.Length.ToString();
postWithParamsClient.UploadStringAsync(address, "POST", string.Empty);

private void postWithParamsClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
  if (e.Error == null)
    MessageBox.Show("WebClient: " + e.Result);
  else
    MessageBox.Show("WebClient: " + e.Error.Message);
}

当我执行上述代码时,它适用于第一个被注释掉的 URL。但是,当我执行第二个代码时,我得到了一般的“NotFound”错误。Fiddler 中没有发布任何内容。所以我把有问题的网址粘贴到“作曲家”中。当我执行请求时,它按预期工作。

我究竟做错了什么?为什么我不能调用那个特定的端点?它在提琴手中工作。它适用于 JQuery。我只是无法让它从 SL for WP 中工作。

感谢您的任何见解。

4

1 回答 1

1

我建议尝试对参数进行编码。

string url = string.Format("http://m.mydomain.com/1.0/services/logException?p1=WindowsPhone&p2=a&p3=b&p4={0}&p5=someuser&p6=test&p7=info&p8=data", HttpUtility.UrlEncode("2012-05-01T14:57:32.8375298-04:00"));

另外,一般来说:您不是在这里执行 POST 请求,而是执行 GET 请求。Content-Length 不应设置为 URL 的长度,而应设置为 POST 数据的长度(在本例中为 string.Empty)。

实际上,您可以调用 DownloadStringAsync(url) 来实现相同的目的,因为您没有发布任何内容。

WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(url));

要实现 POST 请求,您可以尝试以下操作:

string url = "http://m.mydomain.com/1.0/services/logException";
string postdata = string.Format("p1=WindowsPhone&p2=a&p3=b&p4={0}&p5=someuser&p6=test&p7=info&p8=data", HttpUtility.UrlEncode("2012-05-01T14:57:32.8375298-04:00"));

WebClient postWithParamsClient = new WebClient();
postWithParamsClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);

postWithParamsClient.Headers["Content-Length"] = postdata.Length.ToString();
postWithParamsClient.UploadStringAsync(new Uri(url), "POST", postdata);

private void postWithParamsClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
  if (e.Error == null)
    MessageBox.Show("WebClient: " + e.Result);
  else
    MessageBox.Show("WebClient: " + e.Error.Message);
}

此外,MessageBox 可能会抛出 InvalidOperationException(跨线程)。如果是这样,请像这样调用它们:

private void postWithParamsClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
  Dispatcher.BeginInvoke(() => {
    if (e.Error == null)
      MessageBox.Show("WebClient: " + e.Result);
    else
      MessageBox.Show("WebClient: " + e.Error.Message);
  });
}
于 2012-06-07T20:01:28.113 回答