Question about "Network on main thread" exceptions

Kevin

Well-Known Member
Licensed User
Longtime User
Ever since setting my target SDK version higher in order to fix another issue, my app has suddenly been plagued with these dreaded Network on Main Thread exceptions. I spent all day yesterday changing code to avoid anything like this:

B4X:
Sub HttpClient1_ResponseSuccess (Response As HttpResponse, TaskId As Int)
  Result = Response.GetString("UTF8")
End Sub

Just so I understand, it is only the act of calling Result = Response.GetString("UTF8") as shown above that can cause this, correct?

In other words, it is still okay to use HttpClient for sending simple requests so long as we don't try getting the result directly from the response, right? As with HttpUtils (1), I do still use it but it never calls that but rather it uses:

B4X:
Response.GetAsynchronously("response", File.OpenOutput(TempFolder, TaskId, False), True, TaskId)

There are a few instances in my app where it just makes more sense to use the simple HttpClient and even the original HttpUtils. But after spending an entire day messing with this, I want to be sure I am actually fixing the problem. Unfortunately I can't get it to repeat very easily on my Galaxy S3 (Jelly Bean) even though I see reports in my console claiming it happens all the time to others. :(
 

Kevin

Well-Known Member
Licensed User
Longtime User
HttpUtils2 is definitely easier and I am using it for some things. One problem though is that it is more limited than the original HttpUtils. For example, how can I adjust the timeout? How can I add a custom header?

Also, even if there is a response from the device/server, it seems to automatically categorize it as failed if the response does not contain the "200" code. In most cases this is fine, but I have a situation where I'd still like to process the full response but can't seem to do that with HttpUtils2. In my case I was originally looking at whether it failed or succeeded, assuming when it failed it couldn't connect at all. However, I eventually figured out that it was showing failed even though it actually did connect to it... it just happened to return a "forbidden" code which HttpUtils2 returned as failed. Technically it did fail for most typical purposes, but I needed to know if it returned "forbidden" or if it simply didn't connect.

I'm guessing it was made simple intentionally but sometimes we also need more flexibility. :)

BTW, I am using the library.
 
Last edited:
Upvote 0
Top