【发布时间】:2016-08-26 20:59:25
【问题描述】:
我创建了与身份验证服务器 (OAuth 2.0) 的连接以获取令牌。执行此操作的方法如下:
public static async Task<String> GetToken(string username, string password)
{
String response = null;
await Task.Run(() =>
{
URL url = new URL(Configuration.Configuration.baseURL + Configuration.Configuration.tokenPath);
HttpURLConnection urlConnection = (HttpURLConnection)url.OpenConnection();
urlConnection.DoOutput = true;
urlConnection.DoInput = true;
urlConnection.RequestMethod = "POST";
urlConnection.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("client_id", "widas_servicebar"),
new KeyValuePair<string, string>("scope", Configuration.Configuration.scopes)
});
//var content = new Dictionary<string, string>();
//content.Add("grant_type", "password");
//content.Add("username", username);
//content.Add("password", password);
//content.Add("client_id", "widas_servicebar");
//content.Add("scope", Configuration.Configuration.scopes);
using (var streamWriter = new StreamWriter(urlConnection.OutputStream))
{
streamWriter.Write(content);
streamWriter.Flush();
streamWriter.Close();
}
urlConnection.Connect();
var stream = urlConnection.InputStream;
using (var streamReader = new StreamReader(stream))
{
response = streamReader.ReadToEnd();
return response;
}
});
return response;
}
不幸的是,当我调试代码时,它总是卡在 var stream = urlConnection.InputStream; 并且从那里不再发生任何事情(我尝试等待 15 分钟并使用 Postman 请求在 200-500 毫秒内得到响应)。
我对其他一些方法使用了几乎相同的代码,这些方法也建立了与服务器(内容服务器)的连接,并且这些方法正常工作。
我的代码中是否有任何错误,或者输入流永远不会完成的原因是什么?
如果它很重要:我正在构建一个 Xamarin.Android 项目。
【问题讨论】:
-
SO 中有另一个类似的线程,很抱歉现在找不到它的 url,其中一个投票率最高的答案(虽然不被接受)说,只有当他们在语句上设置断点时才会出现问题他们在哪里访问输入流 :) 在你的情况下 var streamWriter = new StreamWriter(urlConnection.OutputStream) 所以如果你在那里放置断点,请将其删除并将其放在返回响应中;检查是否有响应:) 我遇到了同样的问题,我说它有效,但我知道听起来有点疯狂值得一试,让我知道它是否有效:) 直到那时让我找到链接:)
-
它不起作用:/如果您能找到链接,那就太好了。我也会在网上多搜索一下,希望能找到答案。
标签: android xamarin oauth-2.0 httpurlconnection