C#: autenticazione Esempio di chiamata alla funzione di autenticazione La chiamata usa la funzione user_authentication passando - la userid e la password di accesso alle API: interface_code e interface_password
- la userid e la password di un utente Documatica: user@acme.it e user_pass
Il codice elabora anche la risposta, producendo OK in caso di successo e il codice di errore in caso di fallimento. Il codice utilizza la libreria NewtonSoft per trattare le strutture JSON. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Net; using System.IO;
namespace AuthenticationProgram { public class AuthenticationJson { public string message_type = "USER_AUTHENTICATION"; public string interface_code = "interface_code"; public string interface_password = "interface_password"; public string login = "login"; public string password = "password"; public string version = "1.0"; }
class Program { static void Main(string[] args) { string response = ""; string status = ""; JObject responsejson = null; HttpWebRequest webrequest = null; HttpWebResponse webresponse = null;
AuthenticationJson authenticationJson = new AuthenticationJson(); string json = ""; string url = "https://docubank.kpnqwest.it/backend/v1.0/public/script/"; StreamWriter streamwriter = null; string comment = "";
json = JsonConvert.SerializeObject(authenticationJson); try { webrequest = (HttpWebRequest)WebRequest.Create(url); webrequest.ContentType = "application/json"; webrequest.Method = "POST"; webrequest.ContentLength = json.Length; streamwriter = new StreamWriter(webrequest.GetRequestStream()); streamwriter.Write(json); streamwriter.Close(); } catch (Exception e) { responsejson =
JObject.Parse
(string.Format("{comment:\"Exception;\", status:{0}}", e.ToString())); }
try { webresponse = (HttpWebResponse)webrequest.GetResponse(); } catch (WebException we) { webresponse = (HttpWebResponse)we.Response; }
using (
StreamReader
streamreader = new StreamReader(webresponse.GetResponseStream())
) { response = streamreader.ReadToEnd(); streamreader.Close(); }
responsejson = JObject.Parse(response);
status = (string)responsejson["status"]; comment =(string)responsejson["comment"]; if (status == "OK") { Console.WriteLine
("Status:OK \nComment:Authentication success"); } else { Console.WriteLine
(string.Format("Status:{0}\nComment:{1}",status,comment)); }
Console.ReadLine(); } } } |