Android Question Need some help with OK Http

Danie Steyn

Member
Licensed User
Longtime User
Hello. Please excuse my stupidity, I "sort off" know my way around B4x by now, but I am stuck with sending a document using UltraMSG api.
I got some sample code from there site for Java OKHttp
Sample Code:
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
            .add("token", "{TOKEN}")
            .add("to", "")
            .add("filename", "hello.pdf")
            .add("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
            .add("caption", "document caption")


            .build();

Request request = new Request.Builder()
  .url("https://api.ultramsg.com/{INSTANCE_ID}/messages/document")
  .post(body)
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .build();

Response response = client.newCall(request).execute();
 
 System.out.println(response.body().string());

After some searching I kind off translated it to this
My B4Code:
Dim WAToken As String = "mytoken"
    Dim WAInstance As String = "myinstanceid"
    Dim WAURL As String = "https://api.ultramsg.com/"& WAInstance & "/messages/document"
Dim j As HttpJob
    j.Initialize("", Me)
    
    Dim bodymap As Map
    bodymap.Initialize
    bodymap.Put("token", WAToken)
    bodymap.Put("to", "278312345678")
    bodymap.Put("filename", "hello.pdf")
    bodymap.Put("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
    bodymap.Put("caption", "New Order")
    j.PostMultipart(WAURL, bodymap, Null)
    j.GetRequest.SetHeader("token",WAToken)
    
     ' or whatever you need to set. Do it here
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
    End If
    j.Release

But when I run this code I get a response {"error":"Wrong token. Please provide token as a GET parameter."}


Is there anyone that can help me with this.
I can do it in VB.net with the code below
My VB.net Code:
Dim fi As FileInfo = New FileInfo(FileName)

        Dim WebRequest As HttpWebRequest
        Dim bytes As Byte() = IO.File.ReadAllBytes(FileName)
        Dim file As String = Convert.ToBase64String(bytes)
        WebRequest = HttpWebRequest.Create("https://api.ultramsg.com/" & WAInstanceID & "/messages/document")
        Dim postdata As String = "token=" & WAToken & "&to=27" & MobileNumber & "&document=" & HttpUtility.UrlEncode(file) & "&filename=" & fi.Name
        Dim enc As UTF8Encoding = New System.Text.UTF8Encoding()
        Dim postdatabytes As Byte() = enc.GetBytes(postdata)
        WebRequest.Method = "POST"
        WebRequest.ContentType = "application/x-www-form-urlencoded"
        WebRequest.GetRequestStream.Write(postdatabytes, 0, postdatabytes.Length)

        ' print return
        Dim ret As New System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream())
        Dim RetStr As String
        RetStr = ret.ReadToEnd()
 

MarcoRome

Expert
Licensed User
Longtime User
I see in your code that you invoke the token twice
bodymap.Put("token", WAToken)
and
j.GetRequest.SetHeader("token",WAToken)

Try so:
B4X:
Dim WAToken As String = "mytoken"
    Dim WAInstance As String = "myinstanceid"
    Dim WAURL As String = "https://api.ultramsg.com/"& WAInstance & "/messages/document"
Dim j As HttpJob
    j.Initialize("", Me)
    
    Dim bodymap As Map
    bodymap.Initialize
    bodymap.Put("token", WAToken)
    bodymap.Put("to", "278312345678")
    bodymap.Put("filename", "hello.pdf")
    bodymap.Put("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
    bodymap.Put("caption", "New Order")
    j.PostMultipart(WAURL, bodymap, Null)
    j.GetRequest.SetContentType("application/x-www-form-urlencoded")
 
Upvote 0

Danie Steyn

Member
Licensed User
Longtime User
I see in your code that you invoke the token twice
bodymap.Put("token", WAToken)
and
j.GetRequest.SetHeader("token",WAToken)

Try so:
B4X:
Dim WAToken As String = "mytoken"
    Dim WAInstance As String = "myinstanceid"
    Dim WAURL As String = "https://api.ultramsg.com/"& WAInstance & "/messages/document"
Dim j As HttpJob
    j.Initialize("", Me)
   
    Dim bodymap As Map
    bodymap.Initialize
    bodymap.Put("token", WAToken)
    bodymap.Put("to", "278312345678")
    bodymap.Put("filename", "hello.pdf")
    bodymap.Put("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
    bodymap.Put("caption", "New Order")
    j.PostMultipart(WAURL, bodymap, Null)
    j.GetRequest.SetContentType("application/x-www-form-urlencoded")
Yes, I've just added that to see if it doesn't work
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
test

check
j.GetRequest.SetContentType("application/x-www-form-urlencoded")
' j.GetRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded") '???
B4X:
Public Sub TestURLPostMultipart
    Dim WAToken As String = "mytoken"
    Dim WAInstance As String = "myinstanceid"
    Dim WAURL As String = $"https://api.ultramsg.com/${WAInstance}/messages/document"$

    Dim BodyMap As Map
    BodyMap.Initialize
    BodyMap.Put("token", WAToken)
    BodyMap.Put("to", "")
    BodyMap.Put("filename", "hello.pdf")
    BodyMap.Put("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
    BodyMap.Put("caption", "document caption")
    
    Wait For (HttpPostMultipart(WAURL, BodyMap, Null)) Complete (DataResult As String)
    Log(DataResult)
End Sub

Private Sub HttpPostMultipart (URL As String, BodyMap As Map, FileList As List) As ResumableSub
    Dim Result As String
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostMultipart(URL, BodyMap, FileList)
        j.GetRequest.SetContentType("application/x-www-form-urlencoded")
'        j.GetRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded") '???
        j.GetRequest.Timeout = 60 * DateTime.TicksPerSecond
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Result = j.GetString
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return Result
End Sub

Use Postman
See:
 
Upvote 0

Danie Steyn

Member
Licensed User
Longtime User
{"error":"something went wrong please try again"}test

check

B4X:
Public Sub TestURLPostMultipart
    Dim WAToken As String = "mytoken"
    Dim WAInstance As String = "myinstanceid"
    Dim WAURL As String = $"https://api.ultramsg.com/${WAInstance}/messages/document"$

    Dim BodyMap As Map
    BodyMap.Initialize
    BodyMap.Put("token", WAToken)
    BodyMap.Put("to", "")
    BodyMap.Put("filename", "hello.pdf")
    BodyMap.Put("document", "https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf")
    BodyMap.Put("caption", "document caption")
   
    Wait For (HttpPostMultipart(WAURL, BodyMap, Null)) Complete (DataResult As String)
    Log(DataResult)
End Sub

Private Sub HttpPostMultipart (URL As String, BodyMap As Map, FileList As List) As ResumableSub
    Dim Result As String
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostMultipart(URL, BodyMap, FileList)
        j.GetRequest.SetContentType("application/x-www-form-urlencoded")
'        j.GetRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded") '???
        j.GetRequest.Timeout = 60 * DateTime.TicksPerSecond
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Result = j.GetString
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return Result
End Sub

Use Postman
See:
Thanks, with j.GetRequest.SetContentType("application/x-www-form-urlencoded") it gives me {"error":"something went wrong please try again"} ,
j.GetRequest.SetHeader("Content-Type", "application/x-www-form-urlencoded") doesn't seem to make a difference.
 
Upvote 0

Spavlyuk

Active Member
Licensed User
The one difference I can spot between your B4A and VB code is that you encode the document in the latter. Obviously errors such as "something went wrong" aren't very helpful. If your VB code is still working, you need to see what the difference between the 2 requests are.
 
Upvote 0

Danie Steyn

Member
Licensed User
Longtime User
I can get it running in Postman, the ohHttp code generated is
postman:
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "token=mytokenhere&to=27834529707&filename=hello.pdf&document=https://file-example.s3-accelerate.amazonaws.com/documents/cv.pdf&caption=Order");
Request request = new Request.Builder()
  .url("https://api.ultramsg.com/instance1234/messages/document")
  .method("POST", body)
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .build();
Response response = client.newCall(request).execute();
 
Upvote 0

Danie Steyn

Member
Licensed User
Longtime User
I don't know if this is pretty this is, but it works. I managed to convert my VB.net code to send. I'll share incase it might help someone in future.
Working Code:
Dim j As HttpJob
    j.Initialize("", Me)
    Base64Con.Initialize
    Dim B64FileName As String = Base64Con.EncodeFromImage(Starter.Provider.SharedFolder,"Order.pdf")
   
    Dim poststr As String = "token=" & WAToken & "&to=" & "27831234567" & "&document=" & StrUtils.EncodeUrl(B64FileName,"UTF8") & "&filename=" & "Order.pdf"
    j.PostString("https://api.ultramsg.com/" & WAInstance & "/messages/document",poststr)
    j.GetRequest.SetContentType("application/x-www-form-urlencoded")
   
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
       
    End If
    j.Release
Firstly I convert the pdf file to base64, then I can just send everything as text using httpJob.PostString
 
Upvote 0
Top