Android Question Call to WebApi method

Denis De Pauli

Member
Licensed User
I'm sorry if question was previously submitted but I'm not able to find a way to do convert this c# code (made as test).

I have no idea of how I can call a method of a class (I know how to do in c#)

B4X:
 public string Test(string Procedure,string Method , Dictionary<string, string> parametri)
        {
            // URL is something like http://www.mysite.com/Service/WebApiClass
            _client = WebRequest.Create(_url);

            // HOW can I translate this in B4A?
            _client.Method = Procedure;

            _client.Headers.Clear();
            _client.Headers.Add("ID_NOERROR", "-1");
            _client.Headers.Add("ID_AUTOPROXY", "-1");
            _client.Headers.Add("ID_TYPE", Procedure);
          
            if (_token != "")
                _client.Headers.Add("token", Crypt(_token));

            if (_idCliente!="" )
                _client.Headers.Add("idcliente", Crypt(_idCliente));

            if (parametri != null)
            {
                foreach (KeyValuePair<string, string> pair in parametri)
                {
                    _client.Headers.Add(pair.Key, pair.Value);
                }
            }

            String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_username + ":" + _password));
            _client.Headers.Add("Authorization", "Basic " + encoded);
            string resp = "";

            try
            {
                WebResponse webResponse = _client.GetResponse();
                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), true);
                resp = streamReader.ReadToEnd();
                streamReader.Close();
             }
            catch (Exception ex)
            {
                //Log Error
                resp = null;
            }

            return resp;

        }
 

MarkusR

Well-Known Member
Licensed User
Longtime User
try if the server accept http post + json.
if u can modify the web api controller add a template function that return a class object which u need as input at post.

some code i used for calling a web api interface via http post, the object serialization is in JSON string.
B4X:
OkHttp V1.20
OkHttpUtils2 V2.70
DateUtils V1.05
JSON V1.10
Phone V2.50
SQL V1.50

Sub Send() As Boolean

    Dim D As String
    DateTime.DateFormat = "yyyy/MM/dd"
    DateTime.TimeFormat = "HH:mm:ss"
    D = DateTime.Date(DateTime.Now) & " " & DateTime.Time(DateTime.Now)

    '1971-12-31 00:00:00.0000000

    Dim Map1 As Map
    Map1.Initialize
    Map1.Clear

    Map1.Put("FailureId",0)
    Map1.Put("FailureDateTime",D)
    Map1.Put("CompanyId",0)
    Map1.Put("UserId",0)
    Map1.Put("UserName",AutoCompleteEditTextUserName.Text)
    Map1.Put("Trouble",EditTextTrouble.Text)
    Map1.Put("Note",EditTextNote.Text)
    Map1.Put("Location",AutoCompleteEditTextLocation.Text)
    Map1.Put("GPS_ALTITUDE_METER",0.0)
    Map1.Put("GPS_LATITUDE_DEGREE",0.0)
    Map1.Put("GPS_LONGITUDE_DEGREE",0.0)

    '------------ Prüfen

    If Map1.Get("UserName")="" Then
        ToastMessageShow("Name eingeben ..",False)
        Return False
    End If
    
    If Map1.Get("Trouble")="" Then
        ToastMessageShow("Problem eingeben ..",False)
        Return False
    End If

    If Map1.Get("Location")="" Then
        ToastMessageShow("Ort eingeben ..",False)
        Return False
    End If
    
    '------------

    Dim JSON As JSONGenerator
    JSON.Initialize(Map1)
        
    Dim data As String =   JSON.ToPrettyString(1)
    
    Log(data)
    
    Dim Job As HttpJob
    Job.Initialize("Job1",Me)
    Job.Username=Main.API_User
    Job.Password=Main.API_Password
    
    Job.PostString("https://abc.name.com/failure" , data )
    Job.GetRequest.SetContentType("application/json") 'need okhttp lib

    Return True

End Sub

Sub JobDone(Job As HttpJob)
    
    Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
    If Job.Success = True Then
        Select Job.JobName
            Case "Job1"

                Log(Job.GetString)
                If Job.GetString.StartsWith(Chr(34) & "OK" & Chr(34) ) Then 'das ist ja mal Panne^^
                    ToastMessageShow(Job.GetString,True)
                    StartActivity(ActivityThanks)
                    Activity.Finish
                Else
                    ButtonSend.Enabled=True
                    ToastMessageShow("Error: " & Job.GetString, True)
                End If
            Case "JobTemplate"
                Log(Job.GetString)
        End Select
    Else
        ButtonSend.Enabled=True
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
    
End Sub
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Everything you posted should translate to B4A except maybe for this. I could not find a "Crypt" method/function for C#, so what is this? As to
_client.Method = Procedure;
You'll have to call the appropriate method for a HttpJob. Download/Download2 for GET and PostBytes/PostString/PostFile for POST. See https://www.b4x.com/android/help/httputils2.html
Dictionary<string, string> parametri
Use a Map for this
_client.Headers.Add("ID_NOERROR", "-1");
See https://www.b4x.com/android/forum/threads/set-http-request-header-with-okhttputils2.39413/#content
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_username + ":" + _password));
_client.Headers.Add("Authorization", "Basic " + encoded);
Look at @MarkusR's example, where the relevant code is
Job.Username=Main.API_User
Job.Password=Main.API_Password
As to a general overview how to process an HttpJob, see https://www.b4x.com/android/forum/threads/b4x-okhttputils2-with-wait-for.79345/ (Watch the video!)
Note: @MarkusR's example is the "old" way of processing HttpJob. There is nothing wrong with that, except that @Erel will most likely ask why you are not using the new way.
 
Upvote 0

MarkusR

Well-Known Member
Licensed User
Longtime User
wait for is easier to use because u can handle the answer event in one sub, but it's still a non brake waiting loop.
i also prefer wait for event.
 
Upvote 0

Denis De Pauli

Member
Licensed User
Everything you posted should translate to B4A except maybe for this. I could not find a "Crypt" method/function for C#, so what is this?
Opsss.. it's a function that encodes content (not important in this context)

You'll have to call the appropriate method for a HttpJob. Download/Download2 for GET and PostBytes/PostString/PostFile for POST. See https://www.b4x.com/android/help/httputils2.html

This is the hard thing for me.. I've seen all docs on HttpJob and I wasn't able to understand.. On the other side I've a class.. and the "method" I call in
B4X:
_client.Method = Procedure;
is the class method that has to be called.

For Example if my class has a method called "login" I use "login" in my WebRequest.Method.. It's a sort (I believe but I'm not sure of a POST to a specific class-method).
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
_client.Method = Procedure;
is the class method that has to be called.
If I go by Microsoft documentation, WebRequest.Method refers to the protocol method to use in the request. In the example given by the documentation, it is set to "POST". If you are using something else in C#, you may want to give us some links in case (like in my case) we may not be C# fluent. We may be able to help out after reading specifications relating to the language property that you are trying to translate to B4A.

Microsoft documentation for WebRequest.Method: https://docs.microsoft.com/en-us/do...tframework-4.7.2#System_Net_WebRequest_Method
W3.org's documentation on methods supported by HTTP requests (see section 5.1.1): https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html

Update 1: Grammer
Update 2: What is the "login" code/procedure that you are referring to? Do you have code for that procedure?
 
Upvote 0

Denis De Pauli

Member
Licensed User
ah ok thank you all... i developed a new way on server side (creating a POST call with a x-http-method-override header and everythin' is fine now).
If somebody wants I can post code (it's in a alfa state) :D
 
Upvote 0
Top