PC SOFT

FORUMS PROFESSIONNELS
WINDEVWEBDEV et WINDEV Mobile

Accueil → WINDEV 25 → WX - Trabalhando com Rest feito com C# e consumindo com Windev, Webdev, Windev Mobile
WX - Trabalhando com Rest feito com C# e consumindo com Windev, Webdev, Windev Mobile
Débuté par BOLLER, 22 jan. 2018 16:56 - 1 réponse
Membre enregistré
3 655 messages
Popularité : +175 (223 votes)
Posté le 22 janvier 2018 - 16:56
Código em C# - POST
//C#
using (var client = new HttpClient())
{

//setup client

client.BaseAddress = new Uri(apiBaseUri + "/Token");

//client.BaseAddress = new Uri(apiBaseUri + "");

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//setup login data

var formContent = new FormUrlEncodedContent(new[]
{

new KeyValuePair("grant_type", "password"),
new KeyValuePair("username", userName),
new KeyValuePair("password", password),
});

HttpResponseMessage responseMessage;
try

{

responseMessage = client.PostAsync("", formContent).Result;

}

catch (EXCEPTION ex)
{
throw;
}

var responseJson = responseMessage.Content.ReadAsStringAsync().Result;

var jObject = JObject.Parse(responseJson);

RETURN jObject.GetValue("access_token").ToString();

}




Código em WL - Exemplo 1
//WL
Procedure WS_LoginToken01(Username string, Password string)

bufResultado is Buffer = ""

IF Username = 1 AND Password = 1 THEN
Username = "adriano"
Password = "1Pnvm"
END

///Metodo nro 1 via HTTPREQUEST

s_parametros is string

s_parametros = "grant_type=%1&password=%2&username=%3"

s_parametros = URLEncode(StringBuild(s_parametros,"password",Password,Username))

IF httpRequest("http://187.195.103.111:8089/Token","","",s_parametros) THEN
bufResultado = HTTPGetResult()
ELSE
Error(ErrorInfo())
END

//{
//"access_token":"PT3jX8camZdWDUJNRiszFuxnw-GKa259E1Eiykt92IWNefIOVpWcW7yVtG3Cr-1K87keWNdFTRN64vjdaPn3vDIR51fUgZaPdtBM7ouJX0iLTjDOwT4xqlthn_rR9svmujSENIlW_wNKidceAmoykIBjXEDz5cuOvwELXVqBBKf1_zSzXTmGMVo7ifV6QiHZ7DuQt_qvJKWx06nR7CBVrA",
//"token_type":"bearer",
//"expires_in":1209599,
//".issued":"Wed, 17 Jan 2018 18:21:50 GMT",
//".expires":"Wed, 31 Jan 2018 18:21:50 GMT"
//}

ArrResultado is array of string

IF bufResultado <> "" THEN

bufResultado = Replace(bufResultado,Charact(34),"")

access_token is string = BuscaValorJson(bufResultado,"access_token:",",token_type:")
token_type is string = BuscaValorJson(bufResultado,"token_type:",",expires_in:")
expires_in is string = BuscaValorJson(bufResultado,"expires_in:",",.issued:")
issued is string = BuscaValorJson(bufResultado,".issued:",",.expires:")
expires is string = BuscaValorJson(bufResultado,".expires:","}")

Add(ArrResultado,access_token)
Add(ArrResultado,token_type)
Add(ArrResultado,expires_in)
Add(ArrResultado,issued)
Add(ArrResultado,expires)

gsToken = access_token

ELSE

gsToken = ""

END

RESULT(ArrResultado)




Código em WL - Exemplo 2
//WL
Procedure WS_LoginToken02(Username string, Password string)

bufResultado is Buffer = ""

IF Username = 1 AND Password = 1 THEN
Username = "adriano"
Password = "1Pnv%k6m"
END

///Metodo nro 2 via RESTSend

cMyRequest is restRequest
cMyRequest..URL = "http://187.195.103.111:8088/Token"
parametros is string = "grant_type=password&password="+Password+"&username="+Username
cMyRequest..Content = URLEncode(parametros)
cMyRequest..Method = httpPost
cMyResponse is restResponse = RESTSend ( cMyRequest )

//Info(cMyResponse..Content)

bufResultado = cMyResponse..Content

//{
//"access_token":"PT3jX8camZdWDUJNRiszFuxnw-GKa259E1Eiykt92IWNefIOVpWcW7yVtG3Cr-1K87keWNdFTRN64vjdaPn3vDIR51fUgZaPdtBM7ouJX0iLTjDOwT4xqlthn_rR9svmujSENIlW_wNKidceAmoykIBjXEDz5cuOvwELXVqBBKf1_zSzXTmGMVo7ifV6QiHZ7DuQt_qvJKWx06nR7CBVrA",
//"token_type":"bearer",
//"expires_in":1209599,
//".issued":"Wed, 17 Jan 2018 18:21:50 GMT",
//".expires":"Wed, 31 Jan 2018 18:21:50 GMT"
//}

ArrResultado is array of string

IF bufResultado <> "" THEN

bufResultado = Replace(bufResultado,Charact(34),"")

access_token is string = BuscaValorJson(bufResultado,"access_token:",",token_type:")
token_type is string = BuscaValorJson(bufResultado,"token_type:",",expires_in:")
expires_in is string = BuscaValorJson(bufResultado,"expires_in:",",.issued:")
issued is string = BuscaValorJson(bufResultado,".issued:",",.expires:")
expires is string = BuscaValorJson(bufResultado,".expires:","}")


Add(ArrResultado,access_token)
Add(ArrResultado,token_type)
Add(ArrResultado,expires_in)
Add(ArrResultado,issued)
Add(ArrResultado,expires)

gsToken = access_token

ELSE

gsToken = ""

END

RESULT(ArrResultado)





//---------------------------------------------------------------------------------------------//




Exemplo 2 do C# (GET)
PUBLIC IEnumerable ConsultaPedidosEmAberto()
{
List lstPedidoAberto = new List();
try
{
string apiGetPeoplePath = "api/Generic/ConsultaPedidosEmAberto";

CarregaToken();

var request = WebRequest.Create(apiBaseUri + apiGetPeoplePath) as WebRequest;

token = GetAPIToken(userName, password, apiBaseUri);

request.Headers.Add("Authorization", "Bearer " + token);

request.Method = "GET";

request.ContentType = "application/json; charset=utf-8";

WebResponse response1 = request.GetResponse();

var stream = response1.GetResponseStream();

var sr = new StreamReader(stream);

var content = sr.ReadToEnd();

lstPedidoAberto = (List)JsonConvert.DeserializeObject(content, lstPedidoAberto.GetType());

response1.Close();

}

catch (EXCEPTION ex)

{

//return ex.Message;

throw;

}

RETURN lstPedidoAberto;

}


Código em WL - Exemplo 1 - GET
Procedure WS_B_Descarga_Consulta(s_token_recebido)

s_resultado is string = ""

s_parametros is string

cMyRequest is restRequest

cMyResponse is restResponse

IF InternetConnecté() = True AND VerificaWebservice("http://187.195.103.111:8088",10000) = True

IF s_token_recebido = ""

s_parametros = "grant_type=%1&password=%2&username=%3"

s_parametros = URLEncode(StringBuild(s_parametros,"password","1Pnv%ky","adriano"))

//Metodo Token

cMyRequest..URL = "http://187.195.103.111:8089/Token"

cMyRequest..Content = s_parametros

cMyRequest..Method = httpPost

cMyResponse = RESTSend ( cMyRequest )

//Info("Seu Token é: ",cMyResponse..Content)

lst_json_retorno is ST_retorno_js

WHEN EXCEPTION IN

Deserialize(lst_json_retorno,cMyResponse..Content,psdJSON)

s_token_recebido = lst_json_retorno.access_token

DO

s_resultado="Erro ao obter resultado "+ExceptionInfo()

END

END//Sem senha

//Metodo Descarga Consulta

ok is boolean

IF s_token_recebido <> "" THEN

cMyRequest..URL = "http://187.195.103.111:8088/api/Generic/ConsultaPedidosEmAberto"

cMyRequest..Content = s_parametros

cMyRequest..Method = httpGet

cMyRequest.Header["Authorization"] = "Bearer " + s_token_recebido

cMyResponse = RESTSend ( cMyRequest )

lst_arr_json_pedidos is array of ST_retorno_pedidos_abertos

HDeleteAll(t022_DescargaAberta)

WHEN EXCEPTION IN

Deserialize(lst_arr_json_pedidos,cMyResponse..Content,psdJSON)

FOR EACH st_pedidos OF lst_arr_json_pedidos

//Info(st_pedidos.DocNum,st_pedidos.CardName)

t022_DescargaAberta.t022_DocEntry = st_pedidos.DocEntry
t022_DescargaAberta.t022_DocNum = st_pedidos.DocNum
t022_DescargaAberta.t022_CardCode = st_pedidos.CardCode
t022_DescargaAberta.t022_CardName = st_pedidos.CardName

ok = HAdd(t022_DescargaAberta)
IF ok = True THEN
s_resultado ="Sucesso ao obter resultado dos pedidos"
END

END

DO

s_resultado ="Erro ao obter resultado dos pedidos "+ExceptionInfo()

END

ELSE

s_resultado ="Erro ao obter token "+ExceptionInfo()

END

ELSE

s_resultado ="Erro ao obter acesso a internet "+ExceptionInfo()

END

t030_logs.t030_access_token = gsToken
t030_logs.t030_datahora = DateSys() + TimeSys()
t030_logs.t030_metodo = "WS_B_DescargaConsulta"
t030_logs.t030_parametros = s_token_recebido
HAdd(t030_logs)

RESULT(s_resultado)



Obrigado Willian pela Força!!!!!

:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Membre enregistré
123 messages
Popularité : +46 (46 votes)
Posté le 22 janvier 2018 - 19:27
8)

--
Atte. Willian Fernando