c# - 重新设置 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();
解决方案
推荐阅读
- angularjs - AngularJS $http.get() 在返回 bool 的本地函数中
- ios - 在函数声明中将函数设置为变量
- javascript - mongo 查询 $near 总是 0 结果
- python - 具有外键关系的对象的石墨烯中的 GraphQL 突变
- java - 为什么接口有一些Object类的方法?
- go - 使用应用程序上下文作为查询的父上下文
- node.js - 结果未定义的 JS。我无法访问此属性
- android - 如何使用 XML 文件制作自定义按钮?
- r - 如何使直方图的 y 轴既是对数又是百分比?
- javascript - 如何将包含所有嵌套数据的firebase文档移动到其他集合?