gpt4 book ai didi

c# - WebRequest 不工作

转载 作者:行者123 更新时间:2023-11-30 18:32:00 26 4
gpt4 key购买 nike

以下代码在 WinForms 和 Windows Phone 8 应用程序中返回错误。

代码

    var jsonData = "jsonStringGoesHere";
var uri = new Uri("urlGoesHere");
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = jsonData.Length;
webRequest.BeginGetRequestStream(ar =>
{
try
{
using (var os = webRequest.EndGetRequestStream(ar))
{
var postData = Encoding.UTF8.GetBytes(jsonData);
os.Write(postData, 0, postData.Length);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}

webRequest.BeginGetResponse(
ar2 =>
{
try
{
using (var response = webRequest.EndGetResponse(ar2))
using (var reader = new StreamReader(response.GetResponseStream()))
{
var received = reader.ReadToEnd();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}, null);
}, null);

错误在 WinForms 中:[System.Net.WebException] = {"The remote server returned an error: (400) Bad Request."}

在 WP8 中 远程服务器返回错误:NotFound

WCF 服务运行良好,因为我已经让它们在 Fiddler 和其他类型的应用程序(例如 Android/iPhone)中运行。

为什么这行不通?

最佳答案

如果我没记错的话,我想我遇到了类似的事情。我认为这与 ContentLength 有关,但我真的不记得了。

这是我最终使用的代码。不确定是否有帮助。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
string json = BuildJSON(TestConvert(tests));
var enc = new UTF8Encoding(false);
request.ContentLength = enc.GetByteCount(json);
using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), enc))
{
requestWriter.Write(json);
requestWriter.Close();
}

关于c# - WebRequest 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com