我想向一个API发送一个帖子请求,其中包含一些他们要求的参数...我最后只是创建了一个字符串,这很难看,但我不知道让它以不同的方式工作的方法。然后我发现了这个WebRequest
课程的很多变化,但不幸的是我无法让它工作。
主要问题可能是因为我并没有真正理解这是如何组合在一起的,但基本上,我一直在使用WebRequest
方法GetResponse
的示例......即使在MSDN上它也有这个,所以我想知道为什么当我尝试在我的代码中调用它时,我没有得到那个选择?同样适用于GetRequestStream
。
How to add parameters into a WebRequest?
*****DBContext()
{
data = "grant_type=" + GRANTTYPE + "&username=" + username + "&password=" + password + "&client_id=" + CLIENTID + "&redirect_uri=" + REDIRECTURI + "&client_secret=" + CLIENTSECRET;
}
public bool Authenticate()
{
byte[] dataStream = Encoding.UTF8.GetBytes(data);
WebRequest webRequest = WebRequest.Create(urlPath);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
return true;
}
我还有一个问题,那就是我什么时候才能让这些东西工作,我应该把它放在回调中。如果它是一部手机,它是否正在运行本地主机?
答案 0 :(得分:1)
Windows Phone的.NET编译包含WebRequest
类的实现,该实现没有用于获取请求流和响应的同步方法,因为这些将阻止UI线程上的执行,直到操作完成。您可以直接使用现有的Begin / End方法与回调委托,或者您可以将这些调用包装在异步扩展中,这将提供您习惯的(或多或少)可读性和功能。我首选的方法是定义扩展,因此我将演示此方法,但它没有回调模式的性能优势。当您需要使用WebRequest
时,它确实具有易于移植的优势。
异步/等待模式
为WebRequest类定义自定义扩展:
public static class Extensions
{
public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.WebRequest wr)
{
if (wr.ContentLength < 0)
{
throw new InvalidOperationException("The ContentLength property of the WebRequest must first be set to the length of the content to be written to the stream.");
}
return Task<System.IO.Stream>.Factory.FromAsync(wr.BeginGetRequestStream, wr.EndGetRequestStream, null);
}
public static System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync(this System.Net.WebRequest wr)
{
return Task<System.Net.WebResponse>.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);
}
}
使用新扩展(确保导入定义了静态Extensions类的命名空间):
public async System.Threading.Tasks.Task<bool> AuthenticateAsync()
{
byte[] dataStream = System.Text.Encoding.UTF8.GetBytes("...");
System.Net.WebRequest webRequest = System.Net.WebRequest.Create("...");
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = dataStream.Length;
Stream newStream = await webRequest.GetRequestStreamAsync();
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
var webResponse = await webRequest.GetResponseAsync();
return true;
}
关于你的最后一点,目前我没有看到足够的信息来了解回调URI是什么,它在哪里定义,以及它如何影响你正在做的事情。