Android Question Post Request to SMS Server

Jakes72

Active Member
Licensed User
Longtime User
Hi Experts,

I am trying to send a Web Request (A JSON string) to an SMS server to send an SMS (Text message to a Phone) to a certain number/s using the following code (I have this working 100% with VB.Net on a website), but not sure if this is the correct way of doing it with B4A?
The 'JobDone' event never fires and the code seems to get stuck?
What am I doing wrong?

B4X:
Sub SendSMS

    Dim ServerURL As String = "https://api.bulksms.com/v1/messages"       
  
    Dim j As HttpJob
    j.Initialize("j", Me)
    j.JobName="SendSMS"
    Dim msg As String = "{""to"": ""+27747428191"",""body"": ""Hello World!"" }"
  
    j.Username="xxxxxx"
    j.Password="xxxxx"

    j.PostString(ServerURL, msg)

End Sub


Sub JobDone (Job As HttpJob)

    If Job.Success = True Then
        Log(Job.GetString)
    Else
        Log("Error: " & Job.ErrorMessage)
    End If
    Job.Release

End Sub


Thank you for your time in advance.

Regards,
Jacques.
 

Jakes72

Active Member
Licensed User
Longtime User
1. Use smart string literal for msg string
2. Use OkHttpUtils2 with Wait For
Hi Aeric,

Thank you for your reply.
I just noticed that I am actually getting the following error (see screenshot).

Please help.

Regards,
Jacques.
 

Attachments

  • Capture.JPG
    Capture.JPG
    116.5 KB · Views: 124
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
1. Post the relevant code. Best is to upload a small project showing the issue
2. Post ERRORS as TEXT as it is text.

The documentation is here. Your request is incomplete

Hi Don,

Thank you for your reply, I appreciate the help from you experts.
You say my request is incomplete, please explain what I have left out?

-----------------------------------------------------------------
My B4A code is really simple, this is what I have so far:

B4X:
Dim ServerURL As String = "https://api.bulksms.com/v1/messages"         
Dim j As HttpJob
j.Initialize("", Me)
j.Username="xxxxxx"
j.Password="xxxxxx"
    
Dim msg As String = "{""to"": ""+27745428191"",""body"": ""Hello World""}"
j.PostString(ServerURL, msg)
j.GetRequest.SetContentType("application/json")
    
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
     Log(j.GetString)
End If
 j.Release


-----------------------------------------------------------------------
This is my 100% working and tested VB.Net code (from my website which I am trying to replicate in B4A):

B4X:
Dim myData as String
Dim strCellPhoneNo as String = "+277235428191"
Dim strMessage as string = "Hello World"
myData = "{""to"": """ & strCellPhoneNo & """, ""body"":""" & strMessage & """}"

Dim myURI As String = "https://api.bulksms.com/v1/messages"         '
Dim request = WebRequest.Create(myURI)

'Put in Account Credentials.
Dim myUsername As String = "xxxx"
Dim myPassword As String = "xxxx"

request.Credentials = New NetworkCredential(myUsername, myPassword)
request.PreAuthenticate = True
request.Method = "POST"
request.ContentType = "application/json"

Dim encoding = New UnicodeEncoding()
Dim encodedData = encoding.GetBytes(myData)

'Send the data to the Server.
Dim stream = request.GetRequestStream()
stream.Write(encodedData, 0, encodedData.Length)
stream.Close()

'Get a response from the Server.
Dim response = request.GetResponse()

'Put the response in a Reader object.
Dim reader = New StreamReader(response.GetResponseStream())

Now the error is get on the B4A code is this: 'Unable to create service co.za.Falconsoft.Golfanywhere.httputils2service: java.lang.RuntimeException: '
But I don't know what the problem is?
I have added the OkHttp & OkHttpUtils2 libraries as references to the project.

Any other help, would be greatly appreciated.
Here is the error:

Logger connected to: Xiaomi Redmi Note 7
--------- beginning of system
--------- beginning of crash
--------- beginning of main
*** Service (httputils2service) Create ***
** Activity (main) Pause, UserClosed = false **
java.lang.RuntimeException: Unable to create service co.za.Falconsoft.Golfanywhere.httputils2service: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3577)
at android.app.ActivityThread.access$1400(ActivityThread.java:200)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1689)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:175)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
at co.za.Falconsoft.Golfanywhere.httputils2service.onCreate(httputils2service.java:56)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3565)
... 8 more
Caused by: anywheresoftware.b4a.B4AUncaughtException
at anywheresoftware.b4a.Msgbox.debugWait(Msgbox.java:210)
at anywheresoftware.b4a.debug.Debug.wait(Debug.java:217)
at anywheresoftware.b4a.shell.Shell.debugPause(Shell.java:544)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:417)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
... 11 more
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **


If you need anything else, please let me know.

Thank you again for your valuable time.

Regards,
Jacques.
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
test:

See:

Library StringUtils SU.EncodeBase64

CALL:
B4X:
    Dim Username As String = "XXXXXX"
    Dim Password As String = "XXXXXX"
 
    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize(CreateMap("to": "+27745428191", "body": "Hello World"))
    Dim Message As String = JSONGenerator.ToPrettyString(2)

    Wait For (SendBulkSMS(Message, Username, Password)) Complete (Result As String)
    Log(Result)

B4X:
Sub SendBulkSMS(Message As String, Username As String, Password As String) As ResumableSub
    Dim ResultURL As String
    Dim SU As StringUtils
    Dim LinkURL As String = "https://api.bulksms.com/v1/messages"
    Dim Authorization As String = $"${Username}:${Password}"$
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostString(LinkURL, Message)
        j.GetRequest.SetHeader("Authorization", "Basic " & SU.EncodeBase64(Authorization.GetBytes("UTF8")))
        j.GetRequest.SetHeader("Content-Type","application/json")
        j.GetRequest.Timeout = 20000
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            ResultURL = j.GetString
        Else
            Log(j.ErrorMessage)
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return ResultURL
End Sub
 
Last edited:
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
Hi Experts,

Your code looks great oparra, far more advanced than mine! :)

You experts are all awesome and thank you for the help so far, however I am still getting the error:
java.lang.RuntimeException: Unable to create service co.za.Falconsoft.Golfanywhere.httputils2service: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException

This occurs about 30 seconds after running the code and then my app also freezes, so the code might work if this problem can be solved first?
Any idea what is wrong here?
 
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
Eish still not working.
Oparra the only Error log I know is the one which I am posting with the error in it (see below).

OK I think I have narrowed it down a bit, it seems the minute that the line to initialise the HttpJob object is callled:

B4X:
j.Initialize("",Me)

It gives the error (after some time):

java.lang.RuntimeException: Unable to create service co.za.Falconsoft.Golfanywhere.httputils2service: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3577)
at android.app.ActivityThread.access$1400(ActivityThread.java:200)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1689)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:175)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
at co.za.Falconsoft.Golfanywhere.httputils2service.onCreate(httputils2service.java:56)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3565)
... 8 more
Caused by: anywheresoftware.b4a.B4AUncaughtException
at anywheresoftware.b4a.Msgbox.debugWait(Msgbox.java:210)
at anywheresoftware.b4a.debug.Debug.wait(Debug.java:217)
at anywheresoftware.b4a.shell.Shell.debugPause(Shell.java:544)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:417)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
... 11 more
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
ResponseError. Reason: , Response: {
"type" : "https://developer.bulksms.com/json/v1/errors#bad-request",
"title" : "Bad Request",
"status" : 400,
"detail" : "'body' cannot be null"
}
{
"type" : "https://developer.bulksms.com/json/v1/errors#bad-request",
"title" : "Bad Request",
"status" : 400,
"detail" : "'body' cannot be null"
}
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Please post the FULL CODE you are using.

The base URL to use for this service is https://api.bulksms.com/v1. The base URL cannot be used on its own; you must append a path that identifies an operation and you may have to specify some path parameters as well.

Based on the error i fear you are using another URL.
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
see log:

my test result:

note: username and password are invalid

Dim Username As String = "XXXXXX"
Dim Password As String = "XXXXXX"


ResponseError. Reason: , Response: {
"type" : "https://developer.bulksms.com/json/v1/errors#authentication-failed",
"title" : "Authentication Failed",
"status" : 401,
"detail" : "Bad credentials"
}
{
"type" : "https://developer.bulksms.com/json/v1/errors#authentication-failed",
"title" : "Authentication Failed",
"status" : 401,
"detail" : "Bad credentials"
}

B4X:
Private Sub TestBulkSMS
    Dim Username As String = "XXXXXX"
    Dim Password As String = "XXXXXX"
 
    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize(CreateMap("to": "+27745428191", "body": "Hello World"))
    Dim Message As String = JSONGenerator.ToPrettyString(2)

    Wait For (SendBulkSMS(Message, Username, Password)) Complete (Result As String)
    Log(Result)
 
'    Dim Authorization As String = $"${Username}:${Password}"$
'    Dim SU As StringUtils
'    Log(Authorization)
'    Log(SU.EncodeBase64(Authorization.GetBytes("UTF8")))
'    Log(Message)
 
End Sub

Sub SendBulkSMS(Message As String, Username As String, Password As String) As ResumableSub
    Dim ResultURL As String
    Dim SU As StringUtils
    Dim LinkURL As String = "https://api.bulksms.com/v1/messages"
    Dim Authorization As String = $"${Username}:${Password}"$
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostString(LinkURL, Message)
        j.GetRequest.SetHeader("Authorization", "Basic " & SU.EncodeBase64(Authorization.GetBytes("UTF8")))
        j.GetRequest.SetHeader("Content-Type", "application/json")
        j.GetRequest.Timeout = 20000
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            ResultURL = j.GetString
        Else
            Log(j.ErrorMessage)
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return ResultURL
End Sub
 
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
@oparra the xxxxx for Username & password is of course not correct, I have just masked it for the sake of posting here.
The fact that you are at least getting a response from the Server is promising, I cannot even get that far!

@Don as far as I can tell I am using the correct URL. I may be dumb, but I'm not that dumb! ;):)
I am trying to attach the project here, but it keeps telling me the file is to large, it is 1.5MB, even if I reduce it to 600KB it still won't allow me to upload it.

Guys, the error really is that I keep getting a java.lang.RuntimeException the minute I try to Initialise the HttpJob object, I would need to fix this error first before I can even test the code you guys have provided.

This is the error:
java.lang.RuntimeException: Unable to create service b4a.example.httputils2service: java.lang.RuntimeException: anywheresoftware.b4a.B4AUncaughtException

Thanks again for all the help!
 
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
Here is all my project info:

I am running Version 10.90 of B4A.
The only libraries I have added to the project are JSON, OkHttp & OkHttpUtils2.
Below is a screenshot of my library versions.
My Tools Platforms is android-30

Here is the complete code:

B4X:
#Region  Project Attributes 
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName: 
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes 
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub Button1_Click
    
    '---------------------------
    'POSSIBLE METHOD 1:
    '---------------------------
    Dim Username As String = "xxxx"
    Dim Password As String = "xxxx"
      
    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize(CreateMap("to": "+27723428191", "body": "Hello World"))
    Dim Message As String = JSONGenerator.ToPrettyString(2)
        
    Wait For (SendBulkSMS(Message, Username, Password)) Complete (Result As String)
    
    
    
    '-----------------------------
    'POSSIBLE METHOD 2:
    '-----------------------------
'    Dim ServerURL As String = "https://api.bulksms.com/v1/messages"
'    
'    Dim j As HttpJob
'    j.Initialize("", Me)
'    j.JobName="SendSMS"
'    j.Username="xxxx"
'    j.Password="xxxx"
'    
'    Dim msg As String = "{""to"": ""+27755428191"",""body"": ""Hello""}"
'    j.PostString(ServerURL, msg)
'    j.GetRequest.SetContentType("application/json")
'    
'    Wait For (j) JobDone(j As HttpJob)
'    If j.Success Then
'        Log(j.GetString)
'    End If
'    j.Release
'    
        
    
End Sub


Sub SendBulkSMS(Message As String, Username As String, Password As String) As ResumableSub
    Dim ResultURL As String
    Dim SU As StringUtils
    Dim LinkURL As String = "https://api.bulksms.com/v1/messages?auto-unicode=true&longMessageMaxParts=30"
    Dim Authorization As String = $"${Username}:${Password}"$
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostString(LinkURL, Message)
        j.GetRequest.SetHeader("Authorization", "Basic " & SU.EncodeBase64(Authorization.GetBytes("UTF8")))
        j.GetRequest.SetHeader("Content-Type","application/json")
        j.GetRequest.Timeout = 20000
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            ResultURL = j.GetString
        Else
            Log(j.ErrorMessage)
        End If
    Catch
        Log(LastException)
    End Try
    j.Release
    Return ResultURL
End Sub


Here is my Manifest:

B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="29"/>
<supports-screens android:largeScreens="true" 
    android:normalScreens="true" 
    android:smallScreens="true" 
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
'End of default text.
 

Attachments

  • Capture.JPG
    Capture.JPG
    70.5 KB · Views: 116
Upvote 0

Jakes72

Active Member
Licensed User
Longtime User
OK guys an update.
I have eventually gotten this &$%#$^%$ thing to work!
I think the problem was that I somehow had a corrupt library, as I re-installed and now it works.

This simple code works 100%:

B4X:
Dim ServerURL As String = "https://api.bulksms.com/v1/messages"
    
Dim j As HttpJob
j.Initialize("", Me)
j.Username="xxxx"    '<---- Put your Username here.
j.Password="xxxx"     '<---- Put your password here
    
Dim msg As String = "{""to"": ""+27755448391"",""body"": ""Hello""}"
j.PostString(ServerURL, msg)
j.GetRequest.SetContentType("application/json")
    
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
     Log(j.GetString)
End If
 j.Release


Hope this can help other guys that want to send an SMS using the BulkSMS.com gateway.

Thanks again experts for all the help, it is always appreciated!
This is a really great forum & product! :)
 
Upvote 0
Top