访问开放端点(HMRC开发人员网站的Hello World API)时遇到问题。
如果没有server_token或OAuth 2.0 access_token,则此端点不受限制。提供的步骤是:
//为他们的Hello World端点构造GET请求
HttpClient客户端= HttpClientBuilder.create()。build(); HttpGet request = new HttpGet(“ https://test-api.service.hmrc.gov.uk/hello/world”); request.addHeader(“ Accept”,“ application / vnd.hmrc.1.0 + json”);
//执行请求
HttpResponse响应= client.execute(request);
我现在尝试按以下步骤在C#中复制这些步骤:
public string RequestHeaders()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://test-api.service.hmrc.gov.uk/hello/world");
request.Method = "GET";
request.ContentType = @"application/vnd.hmrc.1.0+json";
request.Headers.Add("Accept", @"application/vnd.hmrc.1.0+json");
request.Accept = @"application/vnd.hmrc.1.0+json";
request.KeepAlive = true;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
else
return response.StatusCode.ToString() + "</br>" + response.StatusDescription;
}
}
catch (WebException errMsg)
{
return "Error Status Code : " + ((HttpWebResponse)errMsg.Response).StatusCode + "</br>" +
((HttpWebResponse)errMsg.Response).StatusDescription;
}
catch (Exception errMsg)
{
return errMsg.Message + errMsg.StackTrace;
}
}
我得到了错误:
必须使用适当的属性或方法来修改“ Accept”标头。参数名称:c .:第33行中System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName)的名称在System.Net.WebHeaderCollection.Add(String name,String value)的RequestHeaders()处
第33行:是
request.Accept = @“ application / vnd.hmrc.1.0 + json”;
我也尝试过变体:
// request.Headers.Add(header,headerValue);
//request.Headers[HttpRequestHeader.Accept] =标头;
我尝试过:
https://test-api.service.hmrc.gov.uk/hello/world?Accept=application/vnd.hmrc.1.0+json
并获取相应的内联错误消息为
{“代码”:“ ACCEPT_HEADER_INVALID”,“消息”:“接受标头丢失或无效”}
如何修复标头上的parameter:name并按API预期返回“ Hello World”。
似乎我缺少了一些非常简单的内容...