我正在尝试向项目中的Spotify API发出多个Web请求。 我有一个名为strResponseVal的字符串数组,并且我想存储返回到该数组的json的foreach url响应。
我可以提出一个请求。我这样做的方式是通过实例化具有端点“ URL”的客户端并创建对该URL的Web请求。
我该怎么办?
起初我有:
RestClient rClient = new RestClient();
rClient.endPoint = "https://api.spotify.com/v1/me";
strResponse = string.Empty;
strResponse= rClient.getRequest(token);
//Console.WriteLine("\n\n------------------------------------Next API Call------------------------------------");
RestClient pClient = new RestClient();
pClient.endPoint = "https://api.spotify.com/v1/me/playlists";
strResponse = string.Empty;
strResponse = pClient.getRequest(token);
以下是RestClient类:
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class RestClient
{
public string endPoint { get; set; }
public HttpVerb httpMethod { get; set; }
List<Uri> uris;
public RestClient()
{
endPoint = string.Empty;
httpMethod = HttpVerb.GET;
}
public string[] getRequest(Token accessToken)
{
string[] strResponseVal = new string[uris.Count];
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
try
{
uris = new List<Uri>();
uris.Add(new Uri("https://api.spotify.com/v1/me"));
uris.Add(new Uri("https://api.spotify.com/v1/me/playlists"));
Parallel.ForEach(uris, u =>
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(u);
request.ContentType = "application/json";
request.Headers.Add("Authorization", $"Bearer {accessToken.AccessToken}");
request.Method = httpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("error code: " + response.StatusCode);
}
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
for (int i = 0; i < uris.Count; i++)
{
strResponseVal[i] = reader.ReadToEnd();
}
}
}
}
}
});
}
catch
{
}
/*request.ContentType = "application/json";
request.Headers.Add("Authorization", $"Bearer {accessToken.AccessToken}");
request.Method = httpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("error code: " + response.StatusCode);
}
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseVal = reader.ReadToEnd();
}
}
}
}*/
return strResponseVal;
}