我用一种方法一个接一个地调用一个远程REST service
。我在第一次调用中设置accessToken
的值并将其用于第二个请求。
当我运行它时,它会给我错误
The remote server returned an error: (500) Internal Server Error.
以下是代码。
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
Encoding encodingObj = null;
StreamReader streamReaderObj = null;
string grantCode = string.Empty;
string resultString = string.Empty;
string accessToken = string.Empty;
private void Instantiate()
{
grantCode = HttpContext.Current.Request.QueryString["code"].ToString();
webRequest = (HttpWebRequest)WebRequest.Create(Constants.ACCESS_TOKEN_REQUEST + "&code=" + grantCode);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webResponse = (HttpWebResponse)webRequest.GetResponse();
encodingObj = System.Text.Encoding.GetEncoding("utf-8");
streamReaderObj = new StreamReader(webResponse.GetResponseStream(), encodingObj);
resultString = streamReaderObj.ReadToEnd();
JObject parameterCollection = JObject.Parse(resultString);
accessToken = parameterCollection["access_token"].ToString();
//HttpContext.Current.Response.Write("<br/><br/>Code: <br/>" + grantCode);
//HttpContext.Current.Response.Write("<br/><br/>Access Token: <br/>" + accessToken);
webRequest = (HttpWebRequest)WebRequest.Create(Constants.RETRIEVE_CONTEXT_REQUEST + "vista-688/id/Staff01");
webRequest.Method = "GET";
webRequest.Accept = "application/json";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
webResponse = (HttpWebResponse)webRequest.GetResponse();
encodingObj = System.Text.Encoding.GetEncoding("utf-8");
streamReaderObj = new StreamReader(webResponse.GetResponseStream(), encodingObj);
resultString = streamReaderObj.ReadToEnd();
//HttpContext.Current.Response.Write("<br/><br/>Retrieve Context: <br/>" + resultString);
}
这些是来自配置文件的完整的rest api URL:
<add key="GrantCodeRequest" value="https://<location>/AuthorizationServices/provider/authorize?response_type=code&state=mystateid&client_id=mVisum&redirect_uri=http://localhost:1316/RetrieveContext.aspx&scope=read"/>
<add key="AccessTokenRequest" value="https://<location>/AuthorizationServices/oauth/token?client_id=mVisum&state=mystateid&scope=read&client_secret=TESTMVISUM&response_type=token&grant_type=authorization_code&redirect_uri=http://localhost:1316/RetrieveContext.aspx"/>
<add key="RetrieveContextRequest" value="http://<location>/UserContext/rest/context/user/system/"/>
当我只做第二次请求,accessToken
值初始化为有效值时,第二次调用也没有任何异常。这个方法写在一个处理程序中。
任何人都可以告诉我为什么会这样吗? REST Web服务中没有问题。我还试过使用两个单独的Web请求和Web响应对象,但没有任何工作
答案 0 :(得分:0)
尝试使用
WebClient client = new WebClient();
client.Headers["Content-type"] = @"application/json";
Stream data = client.OpenRead(yoururl); ;
StreamReader reader = new StreamReader(data);
string responseFromServer = reader.ReadToEnd();
以上对我来说很好。