首页 > 解决方案 > 重新设置 HTTP 基地址

问题描述

我正在编写一个小型 C# 程序来对 Spotifys API 进行一些 API 调用。

但是我遇到了一个问题,因为我需要调用不同的端点。我曾以为我可以简单地为每次调用重新设置 HTTP 客户端实例基地址,但事实并非如此,或者我尝试做错了。

一些谷歌搜索让我相信我实际上可能错误地使用了 HTTP 客户端(我一直在避免使用 await),但在我走上将所有工作分开的道路之前,我想确认我不只是错过了一些明显的东西. 我已经用注释标记了代码失败的点。

            //initialize client
        HttpClient APIclient = new HttpClient();
        APIclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        APIclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", DeserializedToken.access_token.ToString());


        //API Call of User Info
        //setup clients base url  
        UriBuilder myUriBase = new UriBuilder(baseURIMethod, baseURI);
        myUriBase.Path = "me";
        APIclient.BaseAddress = new Uri(myUriBase.ToString());


        HttpResponseMessage apiresponse = APIclient.GetAsync(APIclient.BaseAddress.ToString()).Result;

        TokenHelper tokenrefresh = new TokenHelper(authCode, redirectURI);
        tokenrefresh.SetupRefreshKeys(DeserializedToken.refresh_token.ToString());
        tokenrefresh.SetMessageContent();


        //Send token request
        //client is instantiated above, not shown for code brevity
        HttpResponseMessage RefreshResponse = client.SendAsync(tokenrefresh.TokenRequest).Result;

        DeserializedToken = JsonConvert.DeserializeObject<TokenResponse>(RefreshResponse.Content.ReadAsStringAsync().Result);
        APIclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", DeserializedToken.access_token.ToString());
        myUriBase.Path = "me/playlists";
        Uri testing = new Uri(myUriBase.ToString());
        // CODE FAILS HERE with This instance has already started one or more requests. Properties can only be modified before sending the first request.
        APIclient.BaseAddress = new Uri(myUriBase.ToString());

        apiresponse = APIclient.GetAsync(APIclient.BaseAddress.ToString()).Result;

        Console.WriteLine(apiresponse.Content.ReadAsStringAsync().Result);

        Console.ReadKey();

标签: c#

解决方案


推荐阅读