Android Question Posting JSON to Web API and Capturing Response

colboy

Member
Licensed User
Longtime User
I have the handheld capturing data and when complete, want to post the verified JSON string back to the server. The URL is in the form http://192.168.0.1/api/upload The URL is purely fictional as it's a real live service. I'm getting an Internal Server Error, but before I pester the web programmer, just wanted to ensure what I'm doing is correct.

B4X:
Sub btnUploadCycleCounts_Click
    Dim lJson As String=GenerateJSON
    
    Dim job2 As HttpJob
    job2.Initialize("Job2", Me)
    job2.PostString(GlobalFunctions.BaseURL&"/api/handheld", lJson)
    job2.GetRequest.SetHeader("Content-Type", "application/json")
    ToastMessageShow("Created",True)
End Sub

Sub JobDone (Job As HttpJob)
   Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   If Job.Success = True Then
      Log(Job.GetString)
   Else
      Log("Error: " & Job.ErrorMessage)
      ToastMessageShow("Error: " & Job.ErrorMessage, True)
   End If
End Sub

If I remove the Set Header, I get the error, Media Type Not Supported. Would welcome any helpful pointers.

Thanks, Colin
 

colboy

Member
Licensed User
Longtime User
1. You don't need to have a JobDone sub. Better and simpler to use Wait For: [B4X] OkHttpUtils2 with Wait For

2. You are not releasing the Job at the end.

3. You should call Job2.GetRequest.SetContentType.

Hi Erel, thanks for your help. I have a slightly different problem now. I now have the following code

B4X:
    Dim Job2 As HttpJob
    Job2.Initialize("Job2", Me)
    Job2.PostString(GlobalFunctions.BaseURL&"/api/handheld", lJson)
    Job2.GetRequest.SetContentType("application/json")
    wait for (Job2) JobDone(Job2 As HttpJob)
    If Job2.Success Then
        btnUploadCycleCounts.Enabled=True
        'Good
    Else
        btnUploadCycleCounts.Enabled=True
        'Bad
    End If
    Job2.release

When I run it the first time, the data is posted correctly, but it never gets to the If Job2.Success part of the code. If I run it again, I get into the Success=False part, but as the data already exists it causes a key violation. I added the code to disable and re-enable the calling button, but now the button never re-enables, so I can't run the code again. Any ideas what's happening?

Colin
 
Upvote 0
Top