Coo*_* Do 10 java post android retrofit retrofit2
我只能从文档中运行hello world示例(GithubService).
问题是当我运行我的代码时,我得到以下错误,里面 onFailure()
使用JsonReader.setLenient(true)在第1行第1列路径$接受格式错误的JSON
我的API采用POST参数值,因此不需要将它们编码为JSON,但它确实以JSON形式返回响应.
对于响应,我得到了使用工具生成的ApiResponse类.
我的界面:
public interface ApiService {
@POST("/")
Call<ApiResponse> request(@Body HashMap<String, String> parameters);
}
Run Code Online (Sandbox Code Playgroud)
以下是我使用该服务的方式:
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------");
}
});
Run Code Online (Sandbox Code Playgroud)
Vis*_*Raj 13
如果你不想要JSON编码的参数,请使用:
@FormUrlEncoded
@POST("/")
Call<ApiResponse> request(@Field("api_key") String apiKey, @Field("app_id") String appId);
Run Code Online (Sandbox Code Playgroud)
小智 5
您应该知道如何对后参数进行编码。@Header下面的注释也很重要。它用于定义 HTTP 标头中使用的内容类型。
@Headers("Content-type: application/json")
@POST("user/savetext")
public Call<Id> changeShortText(@Body MyObjectToSend text);
Run Code Online (Sandbox Code Playgroud)
您必须以某种方式对您的帖子参数进行编码。要使用 JSON 进行传输,您应该添加.addConverterFactory(GsonConverterFactory.create(gson))到您的 Retrofit 声明中。
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(RestConstants.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.build();
Run Code Online (Sandbox Code Playgroud)
问题的另一个来源可能是来自其余后端的 JSON 似乎不正确。您应该使用验证器检查 json 语法,例如http://jsonlint.com/。
| 归档时间: |
|
| 查看次数: |
22099 次 |
| 最近记录: |