2017-07-22 50 views
0

我想通過一個GET請求發送查詢意外的主機,可問題是我不斷收到java.lang.IllegalArgumentException: unexpected host與OkHttp

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

您使用的是wamp服務器嗎? – akhilesh0707

+0

@Akhilesh Patil nope,使用docker,我知道這個url是正確的,因爲我從那裏得到了任何疑問的信息。 – TheMysticalWarrior

+0

您是使用模擬器還是設備? – akhilesh0707

回答

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

所以,你的主機出了問題。請在Postman上測試您的主機或爲其打開新的端口。我同時ping主機 enter image description here

1

所以我不知道是什麼問題,我就無法構建URL,但第二次我手動做字符串中的URL,它工作得很好,一切都做了它對服務器沒問題。

基本上我從這個

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

它工作得很好

+0

主機不應該包含'/ API/7',這就是路徑。 –

2

HttpUrl爲解析字符串我覺得這是更短的解析方法。

HttpUrl url = HttpUrl.parse("http://10.0.2.2/api/7") 
        .addQueryParameter("lat", deviceLat[0]) 
        .addQueryParameter("long", deviceLong[0]) 
        .build();