2017-08-31 27 views
1

ApiClient.java類 -改造返回404個代碼輸入反應

public class ApiClient { 

    public static final String BASE_URL = "https://jsonplaceholder.typicode.com/"; 
    private static Retrofit retrofit = null; 


    public static Retrofit getClient() { 
     if (retrofit==null) { 
      retrofit = new Retrofit.Builder() 
        .baseUrl(BASE_URL) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
     } 
     return retrofit; 
    } 
} 

接口 -

public interface ApiInterface { 

    @POST("posts/1") 
    Call<ModelClass> savePost(); 
} 

在活動的onCreate -

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); 

     Call<ModelClass> call = apiService.savePost(); 
     call.enqueue(new Callback<ModelClass>() { 
      @Override 
      public void onResponse(Call<ModelClass>call, Response<ModelClass> response) { 

       Log.i(TAG,"response is "+response.body()); 
       Log.i(TAG,"response code is "+response.code()); 
      } 

      @Override 
      public void onFailure(Call<ModelClass>call, Throwable t) { 
       // Log error here since request failed 
       Log.i(TAG, t.toString()); 
      } 
     }); 

依賴性我包括在搖籃 -

compile 'com.squareup.retrofit2:retrofit:2.0.2' 
compile 'com.squareup.retrofit2:converter-gson:2.0.2' 

爲什麼翻新會返回404響應代碼。是否有上述代碼有問題? 在此先感謝。

+0

您是否具有Internet權限? – Zoe

+0

是的,我已經添加了。 – sanil

+0

你連接到互聯網嗎?如在設備有一個工作,活動連接?有時,Android操作系統會切斷連接(您已連接,但無法發送或接收數據) – Zoe

回答

1

Bro代碼是很好的問題是與API。 當我在POSTMAN上的POST方法中顯示你的api時,它顯示404 Not Found,所以請檢查你的服務器

但是它沒有顯示空的json對象作爲body,所以可能缺少參數,並且你正在使用404狀態來顯示這是一個不好的練習,只有當這個api不存在時才顯示404,並且使用其他錯誤代碼(如409,422)來處理這種類型的操作,因此您對響應更加清晰