PC SOFT

PROFESSIONAL NEWSGROUPS
WINDEVWEBDEV and WINDEV Mobile

Home → WINDEV 25 → WX - Enviar um arquivo JSON por “REST” para um WebService (SMS Short Code)
WX - Enviar um arquivo JSON por “REST” para um WebService (SMS Short Code)
Started by adrianoboller, May, 16 2016 9:44 PM - 1 reply
Registered member
3,662 messages
Popularité : +175 (223 votes)
Posted on May, 16 2016 - 9:44 PM




Prezados,

Na última semana comecei a elaborar uma rotina em Windev para consumir um WebService o qual esperava receber algumas informações e um arquivo JSON. A ideia do SMS-FACIL é o de uma central que faz a comunicação junto às operadoras mobile para enviar SMS profissional. As informações necessárias são:

• Fone (destinatário)
• Mensagem até 160 caracteres
• Hash de identificação
• Código do Produto

O endereço do ws é http://www.nazatechnology.com.br/gateway/send. O método de comunicação a ser utilizado é POST.
O primeiro aspecto necessário ao nosso estudo se detém na elaboração de um arquivo JSON, o qual é iniciado e terminado pelo caractere “[“ (abre colchete) e “]” (fecha colchete). Já os registros são circundados com chaves e as colunas separadas por vírgula. O Adriano Boller em uma demo fez a seguinte sequência:

sJsonMensagem is string = “[
{
"target":"554192472007",
"message":"Mensagem de teste 1"
},
{
"target":"554192510031",
"message":"Mensagem de teste 2"
}

]


Ao observar podemos tirar algumas conclusões:

Além de ser uma string convencional e ser circundado com colchetes e cada “registro” ser circundado por chaves, temos os registros separados por vírgula.

Para montar essa mesma sequência, dispomos no Windev de uma função denominada “VariantToJSON” a qual montará cada um dos registros com tantas colunas quanto for declarada, então:

bPrim is boolean = True
sJSON is string = "[" + CR
vSMS_JSON is Variant
vSMS_JSON.target = “556299873535
vSMS_JSON.message = “Nao Use esse exemplo, porque não tenho a menor ideia a quem pertenca
sJSON += (bPrim=True?"" ELSE ","+ CR) + VariantToJSON(vSMS_JSON)
bPrim = False
vSMS_JSON.target = “556299213555
vSMS_JSON.message = “Um segundo exemplo de SMS, acentos somente o ‘é’ e o ‘ç’
sJSON += VariantToJSON(vSMS_JSON)
//Nesse ponto temos a Variável sJSON faltando apenas indicar o fechamento
sJSON += CR + "]"
//Ao final a variável vSMS_JSON ficará com o seguinte conteúdo:
[
{
"target":"556299873535",
"message":" Não use esse exemplo, porque não tenho a menor ideia a quem pertença "
},
{
"target":"556299213555",
"message":" Um segundo exemplo de SMS, acentos somente o ‘é’ e o ‘ç’"
}

]
//Essa é a estrutura final de um arquivo JSON de duas colunas (target e message) e dois registros


As especificações de “HEADER” cabeçalho devem ser aquelas anteriormente apontadas, acrescentando-se o tamanho final da variável que conterá o arquivo JSON. Então:

cMyRequest is restRequest
cMyRequest ..URL = " http://www.nazatechnology.com.br/gateway/sendjson/index.php"
cMyRequest..ContentType = "application/json"
cMyRequest..Content = sJsonMensagem
cMyRequest..UserAgent = "SMS_FACIL"
cMyRequest..Header["Content-Length"] = Length(sJsonMensagem)
cMyRequest..Header["Hash"] = “10b9231267e5844f485572e2c3ae14b1
cMyRequest..Header["Produto"] = "10"
cMyRequest..Header["Host"] = " www.nazatechnology.com.br"
cMyRequest..Method = httpPost
cMyResponse is restResponse = RESTSend ( cMyRequest )
IF ErrorOccurred THEN
fSaveText(fExeDir+"\erro.log", ErrorInfo ( errFullDetails ) + CR + sJsonMensagem)
END


A sequência de informações a serem enviadas ao servidor são essas e colocadas devidamente em cada propriedade. O Método utilizado foi o REST através da utilização da função “RESTSend”. Como última informação, descobrimos que se não informar o nome do arquivo (“index.php”) não há a devida comunicação.

Espero que esse pequeno trabalho possa contribuir para a velocidade de desenvolvimento da rotina de comunicação com o ws do SMS-FÁCIL

Fonte: - por Nazareno Fleury (Goiânia)

Curitiba, 16/05/2016 – por José de Mello Júnior

Muito Obrigado pelo compartilhamento desse exemplo

:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Registered member
3,662 messages
Popularité : +175 (223 votes)
Posted on June, 08 2016 - 1:30 AM
Exemplo de Serialize

http://help.windev.com/en-US/…

// Structure to transform into JSON
ST_Product is structure
// <Serialize> allows you to have a different name in JSON
sName is string <Serialize ="ProductName">
nID is int
nQty is int
mValue is currency <Serialize ="Amount">
END
ST_Person is structure
sLastName is string <Serialize ="LastName">
sFirstName is string <Serialize ="FirstName">
dDOB is Date
arrProducts is array of ST_Product
END
arrPersons is array of ST_Person

// Fill the data
nPersonSubscript is int
nProductSubscript is int
nPersonSubscript = ArrayAdd(arrPersons)
arrPersons[nPersonSubscript].sLastName = "Doe"
arrPersons[nPersonSubscript].sFirstName = "John"
arrPersons[nPersonSubscript].dDOB = "19880516"

nProductSubscript = ArrayAdd(arrPersons[mPersonSubscript].arrProducts)
arrPersons[nPersonSubscript].arrProducts[nProductSubscript].mValue = 89.9
arrPersons[nPersonSubscript].arrProducts[nProductSubscript].nID = 12345724
arrPersons[nPersonSubscript].arrProducts[nProductSubscript].nQty = 5
arrPersons[nPersonSubscript].arrProducts[nProductSubscript].sName = "Red jacket"

// Retrieve the JSON code
bufJson is Buffer
Serialize(arrPersons.bufJson, psdJSON
//[ {
// "LastName":"Doe",
// "FirstName":"John",
// "dDOB":"1988-05-16",
// "arrProducts":[ {
// "ProductName":"Red jacket",
// "nID":12345724,
// "nQty":5,
// "Amount":89.9
// } ]
// } ]

// Send the JSON to a site by POST
HTTPCreateForm("JSONForm")
HTTPAddParameter("JSONForm", "JSONPERSON", bufJson)
HTTPSendForm("JSONForm", ...
"http://MySite/MySite_WEB/US/PAGE_Persons.awp", httpPost)




Exemplo de Deserialize

http://help.windev.com/en-US/…

// This example explains how to use the Serialize/Deserialize functions
// with an Array variable.
// These functions can use all types of WLanguage variables.


MyArray is array of strings
bufResult is Buffer

// Adds elements into the array
Add(MyArray, "WINDEV")
Add(MyArray, "WEBDEV")
Add(MyArray, "WINDEV MOBILE")

// Serialize the array in the buffer in JSON
// => Save the array and its entire content in a JSON string
Serialize(MyArray, bufResult, psdJSON)

// Deserialize the JSON buffer
// => Rebuild the WLanguage array from the JSON string
MyRebuiltArray is array of strings
Deserialize(MyRebuiltArray, bufResult, psdJSON)





Exemplo de Structure

http://help.windev.com/en-US/…

// Declare a structure
ProductRef is structure
SCode is int
PdtCode is fixed string on 10
END

// Declare a structure variable
ProductRef is structure
SCode is int
PdtCode is fixed string on 10
END

Armchair is ProductRef

// Handle a member of a structure variable
ProductRef is structure
SCode is int
PdtCode is fixed string on 10
END

Armchair is ProductRef
Armchair:SCode = 7
Armchair:PdtCode = "Furniture"


--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Message modified, June, 08 2016 - 1:31 AM