带有 OkHttp 的意外主机

The*_*ior 1 android get okhttp

我正在尝试通过 get 请求发送查询,问题是我不断收到 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();
Run Code Online (Sandbox Code Playgroud)

感谢所有帮助:)

Dor*_*ean 6

您的问题是该.host(string)方法只需要url的主机部分。删除路径段将起作用。您的代码应如下所示:

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();
Run Code Online (Sandbox Code Playgroud)