我翻譯一個JSON API爲C#的方法,我遇到了一個問題,即在JSON RPC API(POST)說C#HttpWebRequest的「請求頭」,在JSON POST
其他所有方法都需要從認證結果(=的sessionId),或者每pathparameter
;jsessionid=644AFBF2C1B592B68C6B04938BD26965
或每個Cookie(RequestHeader)
JSESSIONID=644AFBF2C1B592B68C6B04938BD26965
我目前的WebRequest方法:
private async static Task<string> SendJsonAndWait(string json, string url, string sessionId) {
string result;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(StreamWriter streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) {
await streamWriter.WriteAsync(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
Stream responseStream = httpResponse.GetResponseStream();
if(responseStream == null)
throw new Exception("Response Stream was null!");
using(StreamReader streamReader = new StreamReader(responseStream)) {
result = await streamReader.ReadToEndAsync();
}
return result;
}
我如何JSESSIONID
參數添加到我的WebRequest?我對WebRequests不是很熟悉,請簡單解釋一下!
謝謝!
您是否嘗試直接添加到您的網址? –
正如@RomEh建議的那樣,您可以將參數添加到Url中作爲查詢字符串參數,或者您可以使用鍵「sessionid」和「json」以及它們的值創建一個字典對象,將其序列化爲json字符串,然後將其添加到請求流。 –