B4J Question HTTPJOB get a request as string?

keirS

Well-Known Member
Licensed User
Is this possible? I need to get the request including the headers and body as a string exactly as it is sent to the server.
 

MarkusR

Well-Known Member
Licensed User
just make a small app that listen on tcp/socket port 80 and you get the http header / data there
u can use the local IP address of 127.0.0.1 or the pc ip or the computer name in local network.
 

keirS

Well-Known Member
Licensed User
I am calling a governments agency REST API's to submit information. I need to keep a log of the HTTP Requests sent to them to get approval to use REST API's in a live system.

If I cant to that would it be possible to use an OKHttp interceptor with HTTPJOB? This one converts request to cURL for example which would be sufficient I think.
 

MarkusR

Well-Known Member
Licensed User
if you have a correct certificate i think a local proxy is no problem as an example on the same pc.
 

Erel

Administrator
Staff member
Licensed User
Code to get the request headers:

1. Change in HttpUtils2Service:
B4X:
Sub Process_Globals
#if B4A or B4J
   Private hc As OkHttpClient
#else
   Private hc As HttpClient
#end if
   Private TaskIdToJob As Map
   Public TempFolder As String
   Private taskCounter As Int
   Public MyInterceptor As JavaObject
End Sub

Sub Service_Create
   If hc.IsInitialized = False Then
       TempFolder = File.DirTemp
       Dim jo As JavaObject = hc
       Dim builder As JavaObject = jo.RunMethod("sharedInit", Array("hc"))
       MyInterceptor.InitializeNewInstance("b4j.example.httputils2service$MyInterceptor", Null) '<-------- change based on package name
       builder.RunMethod("addNetworkInterceptor", Array(MyInterceptor))
       jo.SetField("client", builder.RunMethod("build", Null))
       TaskIdToJob.Initialize
   End If
End Sub

#if Java
import okhttp3.*;
import okhttp3.Interceptor.*;
import java.io.IOException;
public static class MyInterceptor implements okhttp3.Interceptor {
public Headers headers;
public Response intercept(Chain chain) throws IOException {
   Request r = chain.request();
   headers = r.headers();
   return chain.proceed(r);
}
}
#End If
Usage:
B4X:
If job.Success Then
   Dim headers As JavaObject = HttpUtils2Service.MyInterceptor.GetFieldJO("headers")
   Dim names() As Object = headers.RunMethodJO("names", Null).RunMethod("toArray", Null)
   For Each name As String In names
       Dim values As List = headers.RunMethod("values", Array(name))
       Log($"${name}: ${values}"$)
   Next
End If
 
Last edited:

keirS

Well-Known Member
Licensed User
Thanks Erel. Didn't work at first until I realized that I needed to change:

B4X:
 MyInterceptor.InitializeNewInstance("b4j.example.httputils2service$MyInterceptor", Null)
to my package name. This is exactly what I was looking for.
 
Top