Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected host with OkHttp

I am trying to send a query through a get request, the problem is I keep getting java.lang.IllegalArgumentException: unexpected host

   HttpUrl url = new HttpUrl.Builder()
            .scheme("http")
            .host("10.0.2.2" + "/api/" + 7) // This is where the error is coming in
            .addQueryParameter("lat", deviceLat[0])
            .addQueryParameter("long", deviceLong[0])
            .build();


    Request request = new Request.Builder()
            .url(url)
            .build();

Thanks for all help :)

like image 795
TheMysticalWarrior Avatar asked Oct 24 '25 04:10

TheMysticalWarrior


2 Answers

Your issue there is that the .host(string) method is expecting just the host part of the url. Removing the path segments will work. Your code should look like this:

HttpUrl url = new HttpUrl.Builder()
        .scheme("http")
        .host("10.0.2.2") //Just the host (like "google.com", not "google.com/api")
        .addPathSegment("api")
        .addPathSegment("7")
        .addQueryParameter("lat", deviceLat[0])
        .addQueryParameter("long", deviceLong[0])
        .build();


Request request = new Request.Builder()
        .url(url)
        .build();
like image 110
DoruChidean Avatar answered Oct 26 '25 19:10

DoruChidean


I try this code and it worked

HttpUrl url = new HttpUrl.Builder()
            .scheme("https")
            .host("www.google.com")
            .addPathSegment("search")
            .addQueryParameter("q", "polar bears")
            .build();


Request request = new Request.Builder()
            .url(url)
            .build();

So, there is something wrong with your host. Please test your host on Postman or open new port for it. I also ping that host enter image description here

like image 28
nhp Avatar answered Oct 26 '25 18:10

nhp