2017-02-04 61 views
1

我正嘗試將Win7項目中使用的WebClient轉換爲HttpClient以將其用於我的Win8.1系統。將WebClient轉換爲HttpClient

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<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返回成功響應第一槍。

應該怎麼做?

我當然明白我加入了頭,而不是查詢,但我不知道如何添加查詢...

回答

4

UploadValues在MSDN頁說,Web客戶端發送數據的POST請求與application/x-www-form-urlencoded內容 - 類型。所以你必須/可以使用http內容FormUrlEncodedContent

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

謝謝你的幫助。我有同樣的結果。 '錯誤的API請求,無效的api_option' –

+0

您能提供發送到服務器的請求轉儲嗎? (用小提琴手或其他方式)。但是,答案是否能解決你的問題? – Kalten

+0

它做到了,沒有注意到你的錯字錯誤,並有錯誤的網址。謝謝。你從3個小時的搜索中拯救了我,並且頭痛得厲害。我離這不遠,但我正在轉身。 非常感謝 –