我試圖使我的應用程序連接到使用Retrofit 2的本地Web服務,但我總是得到這個錯誤。我確定Web服務正在響應,因爲我在Firefox中使用了一個使@GET請求和返回成功的工具,並返回了正確的JSON。改裝2錯誤:java.net.SocketTimeoutException:未能連接到10000m後的/192.168.86.1(端口8080)
在android中它甚至沒有連接。
這是我的MainActivity:
public class MainActivity extends AppCompatActivity {
private String API_BASE_URL="http://192.168.1.32:8080/economarket-restService/resources/androidTest/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.client(
httpClient.build()
).build();
ContatoService contato = retrofit.create(ContatoService.class);
Call<Contato> repos = contato.listRespos(); //EconomarketService
repos.enqueue(new Callback<Contato>() {
@Override
public void onResponse(Call<Contato> call, Response<Contato> response) {
Contato contato = response.body();
Toast.makeText(getBaseContext(), "Return" + contato.getName(), Toast.LENGTH_LONG).show();
Log.d("Retorno",response.toString());
}
@Override
public void onFailure(Call<Contato> call, Throwable t) {
Toast.makeText(getBaseContext(), "Return" + t.toString(), Toast.LENGTH_LONG).show();
Log.d("Retorno",t.toString());
}
});
}
}
我的接口:
public interface ContatoService {
@GET("retorna/")
Call<Contato> listRespos();
}
模型類(Contato):
public class Contato {
@SerializedName("name")
private String name;
@SerializedName("phone")
private int phone;
@SerializedName("likes")
private int likes;
@SerializedName("location")
private Location location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
模型類(地點):
public class Location{
}
使用手機瀏覽器,而不是服務器本身的Firefox工具。如果你無法連接,這是一個防火牆問題 –
好的,我做到了。我在手機瀏覽器上測試過,它也正確地返回了json。 – Apolo
在您的帖子標題中,「無法連接到/ 192.168.86.1」。這與您的代碼中顯示的URL不一樣 –