Android Question OkHttp to HttpUtils2

Olli73

Member
Licensed User
Longtime User
Hello, I tried to translate the following working code:

Java:
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\n  \"text\": [\n    \"Hello, world!\"\n  ],\n  \"target_lang\": \"DE\"\n\n}");
Request request = new Request.Builder()
  .url("https://api-free.deepl.com/v2/translate")
  .method("POST", body)
  .addHeader("Authorization", "DeepL-Auth-Key myKey")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();

To:


B4X:
    Dim j As HttpJob
    j.Initialize("", Me)
    Dim poststr As String = "https://api-free.deepl.com/v2/translate"
    
    Dim jsonString As String = ""
    jsonString = "{'text': ["
    jsonString = jsonString & "Hello, world!"
    jsonString = jsonString & "]"
    jsonString = jsonString & ",'target_lang': 'DE'}"
    
    j.PostString(poststr, jsonString)
    j.GetRequest.SetHeader("Authorization", "DeepL-Auth-Key myKey")
    j.GetRequest.SetHeader("Content-Type", "application/json")

    Wait For (j) JobDone(j As HttpJob)
    If j.Success = True Then
        Log(j.GetString)
    Else
        Log(j.ErrorMessage)
    End If
    j.Release

But I get everytime an error - without an ErrorMessage.... I dont see the mistake...
 

drgottjr

Expert
Licensed User
Longtime User
for whatever reason, setting the content type using okhttputils2 is a special case:
USE: j.GetRequest.SetContentType("application/json")
NOT: j.GetRequest.SetHeader("Content-Type", "application/json")

and although at guick glance your json looks ok, you should learn to create json strings in the b4x manner:
B4X:
Dim json As JSONGenerator
Dim postmap As Map
postmap.Initialize
Dim phrases As List = Array As String("Hello,World!")
postmap.Put("text", phrases)
postmap.Put("target_lang", "DE")
json.Initialize(postmap)
log(json.tostring)    ' {"target_lang":"DE","text":["Hello,World!"]}
 
Upvote 1

Olli73

Member
Licensed User
Longtime User
for whatever reason, setting the content type using okhttputils2 is a special case:
USE: j.GetRequest.SetContentType("application/json")
NOT: j.GetRequest.SetHeader("Content-Type", "application/json")

and although at guick glance your json looks ok, you should learn to create json strings in the b4x manner:
B4X:
Dim json As JSONGenerator
Dim postmap As Map
postmap.Initialize
Dim phrases As List = Array As String("Hello,World!")
postmap.Put("text", phrases)
postmap.Put("target_lang", "DE")
json.Initialize(postmap)
log(json.tostring)    ' {"target_lang":"DE","text":["Hello,World!"]}
Thank you so much!! Now it is running! (including creating json string in b4x manner ;-))
 
Upvote 0
Top