2016-01-13 84 views
7

我只能從文檔中運行hello world示例(GithubService)。如何使用翻新2進行POST請求?

問題是,當我運行我的代碼,我得到以下錯誤,裏面的onFailure()

使用JsonReader.setLenient(真)接受第1行 列1路$

畸形的JSON

我的API需要POST params值,所以不需要將它們編碼爲JSON,但它確實會在JSON中返回響應。

對於響應,我得到了使用工具生成的ApiResponse類。

我的界面:

public interface ApiService { 
    @POST("/") 
    Call<ApiResponse> request(@Body HashMap<String, String> parameters); 
} 

這裏是我使用的服務:

HashMap<String, String> parameters = new HashMap<>(); 
parameters.put("api_key", "xxxxxxxxx"); 
parameters.put("app_id", "xxxxxxxxxxx"); 

Call<ApiResponse> call = client.request(parameters); 
call.enqueue(new Callback<ApiResponse>() { 
    @Override 
    public void onResponse(Response<ApiResponse> response) { 
     Log.d(LOG_TAG, "message = " + response.message()); 
     if(response.isSuccess()){ 
      Log.d(LOG_TAG, "-----isSuccess----"); 
     }else{ 
      Log.d(LOG_TAG, "-----isFalse-----"); 
     } 

    } 
    @Override 
    public void onFailure(Throwable t) { 
     Log.d(LOG_TAG, "----onFailure------"); 
     Log.e(LOG_TAG, t.getMessage()); 
     Log.d(LOG_TAG, "----onFailure------"); 
    } 
}); 
+0

發佈完整的堆棧跟蹤,但問題是有可能的是,響應的格式不正確。在改造中有很多調試選項,使用它們 – njzk2

回答

8

如果你不想JSON編碼PARAMS使用:

@FormUrlEncoded 
@POST("/") 
Call<ApiResponse> request(@Field("api_key") String apiKey, @Field("app_id") String appId); 
2

你應該知道你想如何編碼post數據。重要的是下面的註釋@Header。它用於在HTTP標頭中定義使用的內容類型。

@Headers("Content-type: application/json") 
@POST("user/savetext") 
    public Call<Id> changeShortText(@Body MyObjectToSend text); 

你必須以某種方式編碼你的後params。要使用JSON傳輸,您應該在您的Retrofit聲明中添加.addConverterFactory(GsonConverterFactory.create(gson))

Retrofit restAdapter = new Retrofit.Builder() 
       .baseUrl(RestConstants.BASE_URL) 
       .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 
       .addConverterFactory(GsonConverterFactory.create(gson)) 
       .client(httpClient) 
       .build(); 

你的問題的另一個來源可能是JSON,這是來自其他後端似乎是不正確的。您應該使用驗證程序檢查json語法,例如http://jsonlint.com/

+1

'@Header不適用於方法'所以不能編譯,我不想編碼爲json,只是發佈原始值 –

+0

糾正 - @Headers(「Content-type:application/json 「) –