I am trying to convert a
WebClient
Win7
HttpClient
Win8.1
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;
}
}
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;
}
}
}
}
HttpRequest
Bad API request, invalid api option
WebClient
The msdn page of UploadValues
say that WebClient send data in a POST request with application/x-www-form-urlencoded
Content-type. So you must/can use FormUrlEncodedContent
http content.
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;
}
}
}
}