我正在尝试使用Retrofit 2让我的应用程序连接到本地Web服务,但我总是收到此错误。我确定Web服务正在响应,因为我在firefox中使用了一个工具来生成@GET请求并返回正常,返回正确的JSON。
在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{
}
答案 0 :(得分:1)
问题解决了!问题是API_BASE_URL,该网址应该只有:
"http://192.168.1.32:8080/"
网址的其余部分应该在界面上:
@GET("economarket-restService/resources/androidTest/retorna/").
这一切都归结为在URL_BASE中声明URL的根目录,并且url目录访问必须在接口上。