【发布时间】:2019-08-21 02:27:19
【问题描述】:
我有一个 Xamarin 项目,我可以在没有标头的情况下对诸如“reqres.in”API 之类的东西进行 GET 调用:
public Task<string> GetData()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
NSUrl url = new NSUrl("https://reqres.in/api/users?page=2");
NSUrlRequest request = new NSUrlRequest(url);
NSUrlSession session = null;
NSUrlSessionConfiguration myConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration;
//config.MultipathServiceType = NSUrlSessionMultipathServiceType.Handover; //for some reason this does not work!!
myConfig.MultipathServiceType = (NSUrlSessionMultipathServiceType)2; //but this works!!
session = NSUrlSession.FromConfiguration(myConfig);
NSUrlSessionTask task = session.CreateDataTask(request, (data, response, error) => {
//Console.WriteLine(data);
//tell the TaskCompletionSource that we are done here:
tcs.TrySetResult(data.ToString());
});
task.Resume();
return tcs.Task;
}
但是我尝试了很多变体,但无法使用类似的技术对标头和正文进行 POST 调用。我试过这样:
public Task<string> GetDataFromInternet()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
NSUrl url = NSUrl.FromString("https://content.dropboxapi.com/2/files/download");
NSUrlRequest req = new NSUrlRequest(url);
var authToken = "Bearer my-access-token";
if (!string.IsNullOrEmpty(authToken))
{
NSMutableUrlRequest mutableRequest = new NSMutableUrlRequest(url);
try
{
NSMutableDictionary dic = new NSMutableDictionary();
dic.Add(new NSString("Authorization"), new NSString(authToken));
dic.Add(new NSString("Dropbox-API-Arg"), new NSString("{\"path\":\"/path/to/my/file.json\"}"));
mutableRequest.Headers = dic;
NSData body = "{\"name\":\"morpheus\", \"job\": \"leader\"}";
mutableRequest.Body = body;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
mutableRequest.HttpMethod = "POST";
req = (NSUrlRequest)mutableRequest.Copy();
}
NSUrlSession session = null;
NSUrlSessionConfiguration myConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration;
myConfig.MultipathServiceType = NSUrlSessionMultipathServiceType.Handover;
session = NSUrlSession.FromConfiguration(myConfig);
NSUrlSessionTask task = session.CreateDataTask(req, (data, response, error) =>
{
//Console.WriteLine(data);
//tell the TaskCompletionSource that we are done here:
tcs.TrySetResult(data.ToString());
});
task.Resume();
return tcs.Task;
}
但这总是返回“无法连接到服务器”。我已经验证,这个带有我的“访问令牌”的 URL 和其他标题和正文数据工作正常。
请告知我可以使这项工作的任何方法。谢谢。
最终修复: 我的代码和“Junior Jiang - MSFT”在解决方案中编写的代码几乎相同。两者都有效,但我发现它们不起作用的真正原因是因为 iOS Bundle Signing 选项中缺少“Entitlements.plist”。由于此文件中包含“多路径 TCP”权利,因此我发现仅选择该选项无济于事。相反,我们必须将其明确包含在“自定义权利”部分中,如下所示:
【问题讨论】:
标签: ios xamarin nsurlsession nsmutableurlrequest nsurlsessiondatatask