Joh*_* P. 2 c# webclient http httpclient request
我正在尝试将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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对HttpClient的第一枪
public static async Task<string> 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的HttpRequest回报,Bad API request, invalid api option而我的WebClient回报是成功的回应。
应该怎么做?
我当然知道我要添加标题而不是查询,但是我不知道如何添加查询...
UploadValuesWeb客户端在msdn页面上说,WebClient在POST请求中以application/x-www-form-urlencodedContent-type 发送数据。因此,您必须/可以使用FormUrlEncodedContenthttp内容。
public static async Task<string> PastebinSharpAsync(string Username, string Password)
{
using (HttpClient client = new HttpClient())
{
var postParams = new Dictionary<string, string>();
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1136 次 |
| 最近记录: |