An exception when using HttpClient.PostAsync() : JniEnvironment+InstanceMethods.CallIntMethod

shirley

New member
Joined
Aug 18, 2024
Messages
2
Programming Experience
5-10
Developing Xamarin Android APP, I encountered an exception when using HttpClient.PostAsync().

The first time using HttpClient.PostAsync() to call function A will be successful.
Then using HttpClient.PostAsync() call function B fails, and calling function B again succeeds.

The program code and exception log are as follows.

// (1) Function code in Connect_Post.xaml.cs
C#:
public async Task<Post_Res> PostRequest_API()
{
    try
    {
        Post_Cmd post_request = new Post_Cmd
        {
            url = "aaa",
            request = "bbb",
        };

        var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(post_request));

        var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

        var myHttpClient = new HttpClient()
        {
            Timeout = TimeSpan.FromSeconds(10)
        };
        var resp = await myHttpClient.PostAsync(URL, httpContent);  // Line 442

        resp.EnsureSuccessStatusCode();

        if (resp.IsSuccessStatusCode)
        {
            var json = await resp.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject<Post_Res>(json);
            {
                return result;
            }
        }
    }
    catch (Exception ex)
    {
        await DisplayAlert("PostRequest_API()", ex.ToString(), "OK");
    }

    return new Post_Res{};
}

// (2) Exception log
Code:
  at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <396118b2b9a04a3d90019e72fdba3dfa>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <396118b2b9a04a3d90019e72fdba3dfa>:0
  at Java.Net.HttpURLConnection.get_ResponseCode () [0x00000] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-29/mcw/Java.Net.HttpURLConnection.cs:511
  at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass46_0.<DoProcessRequest>b__2 () [0x00000] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:438
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:534
  at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319
--- End of stack trace from previous location where exception was thrown ---

  at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x00328] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:438
  at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00286] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:287
  at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506
  at M2J100.Connect_Inverter.PostRequest_Search_Status (System.String mode) [0x00159] in /Connect_Post.xaml.cs:442
  --- End of managed Java.Net.ProtocolException stack trace ---

java.net.ProtocolException: Unexpected status line:
    at com.android.okhttp.internal.http.StatusLine.parse(StatusLine.java:56)
    at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:188)
    at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:129)
    at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:750)
    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:622)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)
 
Last edited by a moderator:
Welcome to the forum. In the future, please put your code (and long error messages) in code tags. Easiest way is to use the button that looks like </> on the toolbar of the text area.
 
Looking at your code and the callstack, I don't think you are doing anything wrong, but rather the web service that you are calling is returning invalid status codes occasionally.

Not directly related to your problem, but it'll be worth fixing is that you should only have a singleton instance of the HttpClient instead of creating a new instance each time. Read the documentation where it tells you to make use of a single instance.
 
Thanks for your suggestion.

Using a singleton instance of HttpClient still results in the same error message.

Currently, adding the "Connection: close" setting to the HttpClient header prevents the error from occurring.
Add Connection: close setting:
var myHttpClient = new HttpClient()
{
    Timeout = TimeSpan.FromSeconds(10)
};
myHttpClient.DefaultRequestHeaders.Add("connection", "close");
 
As I said, the creating multiple instances of HttpClient is NOT directly related to your problem.
 

Latest posts

Back
Top Bottom