Android Question Help me send a POST request

Semendey

Member
Help me send a POST request
I am using OkHttpUtils2 library with wait function
Here is the code for preparing the JSON request

B4X:
    Dim role As Map
    role.Initialize
    role.Put("role", "user")
    role.Put("content", Mes)
            
    Dim data As Map
    data.Initialize
    data.Put("model", model)
    data.Put("format", "json")
    data.Put("messages", role)
    
    data.Put("think", True)
    data.Put("stream", False)
                
    Dim opt As Map
    opt.Initialize
    opt.Put("temperature", "0.7")
    opt.Put("type","0.9")
    data.Put("options", opt)

Then I send it like this

B4X:
    Dim j As HttpJob
    j.Initialize("", Me) 'name is empty as it is no longer needed
    j.GetRequest.Timeout =5000 ' 5 seconds
    j.PostMultipart(link,data, Null)
    j.GetRequest.SetHeader("accept", "application/json")
    j.GetRequest.SetContentType("application/json")


And in response I receive an error message

(MyMap) {model=gpt-oss:120b-cloud, format=json, messages={role=user, content=привет}, think=true, stream=false, options={temperature=0.7, type=0.9}}
ResponseError. Reason: , Response: {"detail":[{"type":"json_invalid","loc":["body",0],"msg":"JSON decode error","input":{},"ctx":{"error":"Expecting value"}}]}

I can't figure out how to properly send a POST request with a payload in JSON format.
Help me
 

zed

Well-Known Member
Licensed User
Your problem stems from sending your Map using PostMultipart, which isn't designed for JSON.
PostMultipart constructs a multipart/form-data request, while your server expects a raw JSON body (application/json).
As a result, the server can't decode your body and returns the json_invalid error.

You need to convert your Map to a JSON string:

Send using PostString (and not PostMultipart).
 
Upvote 0

Semendey

Member
Thank you

I changed the query formation a little

B4X:
    Dim role As Map
    role.Initialize
    role.Put("role", "user")
    role.Put("content", Mes)
    
    Dim role1 As List
    role1.Initialize
    role1.Add(role)
            
    Dim data As Map
    data.Initialize
    data.Put("model", model)
    data.Put("format", "json")

    data.Put("messages", role1)
    data.Put("think", True)
    data.Put("stream", False)
                
    Dim opt As Map
    opt.Initialize
    opt.Put("temperature", "0.7")
    opt.Put("type","0.9")
    data.Put("options", opt)

And sent it like this

B4X:
j.PostString(link,data.As(JSON).ToString)
 
  • Like
Reactions: zed
Upvote 0
Top