2016-01-13 55 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 “) –