2015-06-16 12 views
20

Sto cercando di eseguire il seguente ricciolo (che funziona per me) in C# utilizzando HttpClient.Come utilizzare HttpClient per postare con l'autenticazione

curl -X POST http://www.somehosturl.com \ 
    -u <client-id>:<client-secret> \ 
    -d 'grant_type=password' \ 
    -d 'username=<email>' \ 
    -d 'password=<password>' \ 
    -d 'scope=all 

codice C#:

HttpClientHandler handler = new HttpClientHandler { Credentials = new 
      System.Net.NetworkCredential ("my_client_id", "my_client_secret") 
    }; 


    try 
    { 
     using(var httpClient = new HttpClient(handler)) 
     { 
      var activationUrl = "www.somehosturl.com"; 

      var postData = "grant_type=password&[email protected]&password=mypass&scope=all"; 
      var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); 

      var response = await httpClient.PostAsync(activationUrl, content); 
      if(!response.IsSuccessStatusCode) 
       return null; 

      var result = await response.Content.ReadAsStringAsync(); 

      return result; 
     } 
    } 
    catch(Exception) 
    { 
     return null; 
    } 

Quando eseguito, appena si blocca fuori, pretende anche intercettare l'eccezione

Normalmente sono in grado di GET e POST perfettamente bene, ma che cosa mi ha gettato via è come impostare la roba auth (client-id e client-secret)

+2

Cosa vuoi dire da incidenti? Stai facendo questo all'interno di VS? Hai attivato First Chance Exceptions? –

+0

Dai un'occhiata a questo post StackOverflow per vedere se aiuta: http://stackoverflow.com/a/23914662/1337635 – joehanna

+0

potresti inserire il tuo codice, inclusa la firma del metodo. –

risposta

14

In primo luogo è necessario impostare la Authorization -Intestazione con il <clientid> e <clientsecret>.

Invece di utilizzare StringContent si dovrebbe usare FormUrlEncodedContent come illustrato di seguito:

var client = new HttpClient(); 
client.BaseAddress = new Uri("http://myserver"); 
var request = new HttpRequestMessage(HttpMethod.Post, "/path"); 

var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>"); 
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); 

var formData = new List<KeyValuePair<string, string>>(); 
formData.Add(new KeyValuePair<string, string>("grant_type", "password")); 
formData.Add(new KeyValuePair<string, string>("username", "<email>")); 
formData.Add(new KeyValuePair<string, string>("password", "<password>")); 
formData.Add(new KeyValuePair<string, string>("scope", "all")); 

request.Content = new FormUrlEncodedContent(formData); 
var response = await client.SendAsync(request); 
+2

Dovresti spiegare * perché * questa è una risposta alla domanda. Fai voglio dire che oltre a dover impostare l'intestazione di autenticazione, l'OP passa i dati post nel modo sbagliato? –

+0

Grazie Alexander, funziona alla grande! Sto usando Xamarin anche se non posso usare Encoding.ASCII, ho dovuto usare UTF8Encoding(). GetBytes(). – Jesse

+0

UTF8 ha senso. Ho aggiornato la mia risposta. –

13

Provare a inserire le credenziali direttamente nella proprietà di intestazioni di HttpClient.

using (var client = new HttpClient()) { 
     var byteArray = Encoding.ASCII.GetBytes("my_client_id:my_client_secret"); 
     var header = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray)); 
     client.DefaultRequestHeaders.Authorization = header; 

     return await client.GetStringAsync(uri); 
}