我试图使我的应用程序连接到使用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不一样 –