【问题标题】:URLConnection does not finish getting InputStreamURLConnection 没有完成获取 InputStream
【发布时间】: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


【解决方案1】:

以防万一您不知道:有一个名为 Xamarin.Auth 的 Xamarin 组件提供 OAuth 身份验证。您不必手动实现它:

Xamnarin.Forms 教程:https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/

NuGet:https://www.nuget.org/packages/Xamarin.Auth/

【讨论】:

    【解决方案2】:

    我让它工作了。似乎我尝试使用的东西并没有像我想象的那样起作用。现在工作的代码如下所示:

    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 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);
    
                    Stream os = urlConnection.OutputStream;
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.Write(getQuery(content));
                    writer.Flush();
                    writer.Close();
                    os.Close();
    
                    urlConnection.Connect();
                    //var debug = urlConnection.ErrorStream;
                    var stream = urlConnection.InputStream;
    
                    using (var streamReader = new StreamReader(stream))
                    {
                        response = streamReader.ReadToEnd();                    
                    }
                    return response;
                });
                return response;
            }
    

    getQuery 方法如下所示:

    private static String getQuery(Dictionary<string, string> dictionary)
            {
                StringBuilder result = new StringBuilder();
                bool first = true;
    
                foreach (KeyValuePair<string, string> entry in dictionary)
                {      
                    if (first)
                    {
                        first = false;
                    }          
                    result.Append(URLEncoder.Encode(entry.Key, "UTF-8"));
                    result.Append("=");
                    result.Append(URLEncoder.Encode(entry.Value, "UTF-8"));
                    result.Append("&");
                }
    
                return result.ToString();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      相关资源
      最近更新 更多