gpt4 book ai didi

JSON POST 中的 C# HttpWebRequest "Request Header"

转载 作者:可可西里 更新时间:2023-11-01 17:28:10 36 4
gpt4 key购买 nike

我正在将 JSON API 转换为 C# 方法,我遇到了 JSON RPC API (POST) 说的问题

All other methods require the result from authentication ( = sessionId), either per pathparameter

;jsessionid=644AFBF2C1B592B68C6B04938BD26965

or per 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不是很熟悉,请简单说明一下!

谢谢!

最佳答案

使用Cookies .

你的案例看起来像这样;

private async static Task<string> SendJsonAndWait(string json, string url, string sessionId) {
Uri uri = new Uri(url);
string result;

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

//Add the JSESSIONID Cookie
if(httpWebRequest.CookieContainer == null)
httpWebRequest.CookieContainer = new CookieContainer();

if(!string.IsNullOrWhiteSpace(sessionId))
httpWebRequest.CookieContainer.Add(new Cookie("JSESSIONID", sessionId, "/", uri.Host));

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;
}

关于JSON POST 中的 C# HttpWebRequest "Request Header",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351384/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com