作者:mobiledu2502918245 | 来源:互联网 | 2023-02-12 20:30
我正在尝试将WebClient
过去用于Win7
项目的A转换为HttpClient
在Win8.1
系统上使用的A。
WenClient:
public static void PastebinSharp(string Username, string Password)
{
NameValueCollection IQuery = new NameValueCollection();
IQuery.Add("api_dev_key", IDevKey);
IQuery.Add("api_user_name", Username);
IQuery.Add("api_user_password", Password);
using (WebClient wc = new WebClient())
{
byte[] respBytes = wc.UploadValues(ILoginURL, IQuery);
string resp = Encoding.UTF8.GetString(respBytes);
if (resp.Contains("Bad API request"))
{
throw new WebException("Bad Request", WebExceptionStatus.SendFailure);
}
Console.WriteLine(resp);
//IUserKey = resp;
}
}
这是我对HttpClient的第一枪
public static async Task PastebinSharp(string Username, string Password)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("api_dev_key", GlobalVars.IDevKey);
client.DefaultRequestHeaders.Add("api_user_name", Username);
client.DefaultRequestHeaders.Add("api_user_password", Password);
using (HttpResponseMessage respOnse= await client.GetAsync(GlobalVars.IPostURL))
{
using (HttpContent cOntent= response.Content)
{
string result = await content.ReadAsStringAsync();
Debug.WriteLine(result);
return result;
}
}
}
}
我的HttpRequest
回报,Bad API request, invalid api option
而我的WebClient
回报是成功的回应。
应该怎么做?
我当然知道我要添加标题而不是查询,但是我不知道如何添加查询...
1> Kalten..:
UploadValues
Web客户端在msdn页面上说,WebClient在POST请求中以application/x-www-form-urlencoded
Content-type 发送数据。因此,您必须/可以使用FormUrlEncodedContent
http内容。
public static async Task PastebinSharpAsync(string Username, string Password)
{
using (HttpClient client = new HttpClient())
{
var postParams = new Dictionary();
postParams.Add("api_dev_key", IDevKey);
postParams.Add("api_user_name", Username);
postParams.Add("api_user_password", Password);
using(var postCOntent= new FormUrlEncodedContent(postParams))
using (HttpResponseMessage respOnse= await client.PostAsync(ILoginURL, postContent))
{
response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
using (HttpContent cOntent= response.Content)
{
string result = await content.ReadAsStringAsync();
Debug.WriteLine(result);
return result;
}
}
}
}