2

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 :)

TheFairywarrior
  • 718
  • 1
  • 8
  • 16

4 Answers4

8

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();
DoruChidean
  • 7,941
  • 1
  • 29
  • 33
3

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

phatnhse
  • 3,870
  • 2
  • 20
  • 29
2

HttpUrl has a parse method for parsing Strings which I find to be much shorter.

HttpUrl url = HttpUrl.parse("http://10.0.2.2/api/7")
                     .addQueryParameter("lat", deviceLat[0])
                     .addQueryParameter("long", deviceLong[0])
                     .build();
Bill O'Neil
  • 556
  • 3
  • 13
1

So I have no idea what the problem is that I can't build the URL, but the second that I made the url in the string manually, it worked fine and everything made it to the server no problem.

Basically I changed from this

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();

to this

Request request = new Request.Builder()
                                .url("10.0.2.2" + "/api/" + 7 + "?long=" + deviceLong[0] + "&lat=" + deviceLat[0])
                                .build();

And it worked fine

TheFairywarrior
  • 718
  • 1
  • 8
  • 16