将Httpwebrequest转换为Httpclient



以下是获取令牌的完整代码。我想把它翻译成Httpclient。希望有人能帮我。我想从httpwebrequest切换到httpclient非常感谢你帮我。

public static async Task<TokenInfo> GetToken(string userName, string password)
{
string text = "https://api.site.io/v4/sessions.json?app=100005a&t=1569053071";

string postDataStr = string.Concat(new string[]
{
"{"password": "", password,
"", "login_id": "", userName,""}"
});

var token_info = JObject.Parse(await Post(text, postDataStr));
var token = token_info["token"].ToString();

string user = token_info["user"]["name"].ToString();
string country = token_info["user"]["country"].ToString();

return new TokenInfo()
{
Token = token,
Name = user,
Country = country
};
}
private static HttpWebRequest httpWebRequest;
public static async Task<string> Post(string Url, string postDataStr)
{
var uri = new Uri(Url);
httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "text/plain";
httpWebRequest.KeepAlive = false;
httpWebRequest.ContentLength = (long)Encoding.UTF8.GetByteCount(postDataStr);
using (var writer = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.GetEncoding("gb2312")))
{
await writer.WriteAsync(postDataStr);
}
using (var response = (await httpWebRequest.GetResponseAsync()).GetResponseStream())
{
using (var reader = new StreamReader(response, Encoding.GetEncoding("utf-8")))
{
var result = await reader.ReadToEndAsync();
Console.WriteLine(result);
return result;
}
}
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
HttpClient httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, Url)
{
Content = new StringContent(postDataStr, Encoding.UTF8, "text/plain")
};

using (var response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();

}

下面是一个执行发布请求的示例,类似于您使用HttpClient发布的示例

public static async Task<string> Post(string url, Dictionary<string,string> postParameters)
{
using (HttpClient client = new HttpClient())
{
HttpContent postData = new FormUrlEncodedContent(postParameters);
HttpResponseMessage response = await client.PostAsync(url, postData);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return content;
}
else
{
//Do something when request fails
return string.Empty;
}
}
}

我添加了一个Dictionary<string, string>,而不是方法中的postDataStr参数

假设你想将一些数据发布到一个端点,该端点需要一些数据,如用户名和密码,那么你可以这样做:

Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("Username", "MyUsername");
postData.Add("Password", "MyPassword");
await Post("MyUrl", postData);

如果你更喜欢发送纯字符串而不是使用Dictionary解决方案,你可以这样做:

public static async Task<string> Post(string url, string postDataStr)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Content-Type", "text/plain");
HttpContent postData = new StringContent(postDataStr);
HttpResponseMessage response = await client.PostAsync(url, postData);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return content;
}
else
{
//Do something when request fails
return string.Empty;
}
}
}

最新更新