我正在尝试通过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();
感谢您的帮助:)
答案 0 :(得分:3)
我尝试使用此代码并且有效
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();
答案 1 :(得分:3)
您的问题是.host(string)
方法仅期望网址的 host 部分。删除路径段即可。您的代码应如下所示:
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();
答案 2 :(得分:2)
HttpUrl
有一个解析字符串的解析方法,我觉得它更短。
HttpUrl url = HttpUrl.parse("http://10.0.2.2/api/7")
.addQueryParameter("lat", deviceLat[0])
.addQueryParameter("long", deviceLong[0])
.build();
答案 3 :(得分:1)
所以我不知道我不能构建URL的问题是什么,但是我手动在字符串中创建url的第二个问题,它工作得很好,一切都没问题。< / p>
基本上我改变了这个
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();
到这个
Request request = new Request.Builder()
.url("10.0.2.2" + "/api/" + 7 + "?long=" + deviceLong[0] + "&lat=" + deviceLat[0])
.build();
它运作良好
答案 4 :(得分:0)
试试这个:
HttpUrl.Builder httpUrl = new HttpUrl.Builder();
httpUrl.scheme("http");
httpUrl.host("10.0.2.2");
httpUrl.addPathSegment("api");
httpUrl.addPathSegment("7");
httpUrl.addQueryParameter("lat", deviceLat[0]);
httpUrl.addQueryParameter("long", deviceLong[0]);
HttpUrl build = httpUrl.build();
String result = build.toString();