【问题标题】:How to Retrieve file from URL which Requires Authentication?如何从需要身份验证的 URL 中检索文件?
【发布时间】:2020-02-06 13:59:56
【问题描述】:

我正在 Unity 中制作一个工具来从服务器检索数据。服务器的界面可以提供 URL,我们稍后可以单击这些 URL,这些 URL 将返回一个 XML 或 CSV 文件,其中包含来自该服务器的查询结果。但是,它需要基本身份验证。单击链接时,它只会在给我结果之前弹出一个登录屏幕。如果我尝试我 [认为] 我在 Unity 中所知道的(从 WebRequest.GetResponse() 开始),它只会失败并说我没有被授权。它不显示用于身份验证的弹出窗口。那么,当使用 Unity 访问并等待登录结果以获取文件时,如何让该登录弹出窗口出现?或者是否有一些标准化的方式可以在链接本身中提供该信息?

【问题讨论】:

  • 您需要使用称为身份验证标头的东西。我认为这是一个很好的解释:stackoverflow.com/questions/4334521/…
  • 您说的是哪种身份验证?因为有多种 Auth 方法可用于 API 身份验证。首先你已经弄清楚了,然后,你可以在你的头文件中添加任何内容(通常 API 需要在头文件中发送与身份验证相关的参数,尽管一些 API 也使用 API 密钥作为用户查询)。
  • 如果可以的话,如果你不介意我可以给我一个API链接,以便我可以学习吗?
  • 好像是基本认证。我正在通过上面的链接尝试一些东西,但似乎有很多不同的方法/东西可以尝试。我们会看看它是否能到达任何地方!
  • Egads!谢谢@TomerShahar!这个答案stackoverflow.com/a/13956730/1411541 给了我回复,这帮助我将回复保存到文件中! java2s.com/Tutorial/CSharp/0580__Network/…

标签: c# unity3d authentication url


【解决方案1】:

这里有一些你应该开始使用的代码。只需填写请求链接和用户名、密码即可。请查看代码中的 cmets 以了解其作用。

//try just in case something went wrong whith calling the api
try
{
    //Use using so that if the code end the client disposes it self
    using (HttpClient client = new HttpClient())
    {
        //Setup authentication information
        string yourusername = "username";
        string yourpwd = "password";
        //this is when you expect json to return from the api
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //add the authentication to the request
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", 
            Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes($"{yourusername}:{yourpwd}")));
        //api link used to make the call
        var requestLink = $"apiLink";
        using (HttpResponseMessage response = client.GetAsync(requestLink).Result)
        {
            //Make sure the request was successfull before proceding
            response.EnsureSuccessStatusCode();
            //Get response from website and convert to a string
            string responseBody = response.Content.ReadAsStringAsync().Result;
            //now you have the results
        }
    }
}
//Catch the exception if something went from and show it!
catch (Exception)
{
    throw;
}

【讨论】:

【解决方案2】:

这就是我在查看了上面的 cmets 后最终得到的结果。让我知道我是否在做任何非常低效的事情!

    String username = "Superman"; // Obviously handled secretly
    String pw = "ILoveLex4evar!"; // Obviously handled secretly
    String url = "https://www.SuperSecretServer.com/123&stuff=?uhh";
    String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + pw));
    CookieContainer myContainer = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Headers.Add("Authorization", "Basic " + encoded);
    try
    {
        using (WebResponse response = request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (FileStream xml = File.Create("filepath/filename.xml"))
                {
                    byte[] buffer = new byte[BufferSize];
                    int read;
                    while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        xml.Write(buffer, 0, read);
                    }
                }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多