13

I was only able to run the hello world example (GithubService) from the docs.

The problem is when I run my code, I get the following Error, inside of onFailure()

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

My API takes POST params value, so no need to encode them as JSON, but it does return the response in JSON.

For the response I got ApiResponse class that I generated using tools.

My interface:

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

Here is how I use the service:

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------");
    }
});
4

3 回答 3

17

如果您不想要 JSON 编码的参数,请使用:

@FormUrlEncoded
@POST("/")
Call<ApiResponse> request(@Field("api_key") String apiKey, @Field("app_id") String appId);
于 2016-01-14T02:49:42.237 回答
4

You should be aware of how you want to encode the post params. Important is also the @Header annotation in the following. It is used to define the used content type in the HTTP header.

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

You have to encode your post params somehow. To use JSON for transmission you should add .addConverterFactory(GsonConverterFactory.create(gson)) into your Retrofit declaration.

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

Another source of your problem could be that the JSON, that's coming from the rest backend seems to be not correct. You should check the json syntax with a validator, e.g. http://jsonlint.com/.

于 2016-01-13T21:00:32.433 回答
0

假设我们有一个以下 JSON 字符串,我们想使用 Retrofit 2 将字符串发布到远程 API:

{ "name": "Introduction to Unity3D", "author": "Vishnu Sivan" }

要使用 Retrofit 2 发布 JSON 字符串,我们可以定义一个 POJO 来表示我们需要的 JSON。例如,代表 JSON 的 POJO 可以通过以下方式定义:

public class Book {
 
  private Long id;
  private String name;
  private String author;
 
  // constructor
  // getter and setter
}

然后我们可以定义如下端点:

public interface GetDataService {

    @POST("post")
    Call<Book> addBook(@Body Book book);
}

因为我们用注解对参数进行了@Body注解,Retrofit 2 将使用转换器库将参数序列化为 JSON。

接下来,让我们像使用 Retrofit 2 发布对象一样发布 JSON 字符串:

public void testPostJson() throws IOException {

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://httpbin.org/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    GetDataService service = retrofit.create(GetDataService.class);
    Book book = new Book(1, "Introduction to Unity3D", "Vishnu Sivan");

    call.enqueue(new Callback<Book>() {
        @Override
        public void onResponse(Call<Book> call, Response<Book> response) {
            Book book = response.body();
            Log.d("book", book.getName()); //getName() is the getter method that declared in the Book model class
        }

        @Override
        public void onFailure(Call<com.tcs.artoy.model.Response> call, Throwable t) {
            Log.e("error", t.toString());
        }
    });
}

注意:这里我们得到的响应是我们发送到服务器的相同的 json 格式数据。如果您想要与同一请求对象不同的响应,则在您的项目中创建另一个模型文件并将其作为响应类型提及。

如果你想要一个 POST 请求示例,只需检查以下 Github 存储库:

更多:

https://howtoprogram.xyz/2017/02/17/how-to-post-with-retrofit-2/

于 2022-02-01T14:29:23.397 回答