Android Retrofit - POST 请求不起作用,但在 Postman 中它起作用 [英] Android Retrofit - POST request doesn't work, but in Postman it works

查看:37
本文介绍了Android Retrofit - POST 请求不起作用,但在 Postman 中它起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我得到的错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 1 列路径 $

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

我从 Postman 收到的 JSON 响应:

JSON response I'm getting from Postman:

{
  "title": "test title",
  "body": "test body",
  "userId": 1,
  "id": 101
}

这就是我回应来自其他 API(使用 slim2 框架)的响应的方式:

This is how I echoed the response from the rest API (used slim2 framework):

$app->post('/posts', function() use($app){
    $res = array(
        "title" => $app->request->post('title'),
        "body" => $app->request->post('body'),
        "userId" => 1,
        "id" => 101
        );
    echoResponse(201, $res);
});

echoResponse 方法:

function echoResponse($status_code, $response) {
    $app = SlimSlim::getInstance();
    $app->status($status_code);
    $app->contentType('application/json');

    echo json_encode($response);
}

我调用 API 的方法:

The method where I call the API:

public void sendPost(String title, String body) {
    mAPIService.savePost(title, body, 1).enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {
            Log.i(TAG, "post sendPost to onResponse.");
            if(response.isSuccessful()) {
                showResponse(response.body().toString());
                Log.i(TAG, "post submitted to API." + response.body().toString());
            }
        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {
            Log.e(TAG, "Unable to submit post to API.");
            Log.e(TAG, t.toString());
        }
    });
}

APIServie 接口:

public interface APIService {
@POST("/posts")
@FormUrlEncoded
Call<Post> savePost(@Field("title") String title,
                    @Field("body") String body,
                    @Field("userId") long userId);
}

我是如何得到 retrofit 实例的:

How I got the retrofit instance:

mAPIService = ApiUtils.getAPIService();
public class ApiUtils {
    private ApiUtils() {}
    public static final String BASE_URL = "http://myurl/v1/";

    public static APIService getAPIService() {
        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }

}
public class RetrofitClient {
   private static Retrofit retrofit = null;

   private static Gson gson = new GsonBuilder()
        .setLenient()
        .create();

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

我发布所有这些的原因是我找不到问题出在哪里,因为我从 API 获得的 JSON 响应看起来不错,我调用 API 的方式看起来不错.有很多与此相关的问题可以在这里找到.但我找不到我的问题的答案.请给我一个解决方案.谢谢

Reason I posted all this was I couldn't find where the problem is because JSON response I'm getting from API looks ok, the way I called the API looks ok. There are many questions related to this can be found here. But I couldn't find the answer to my problem. Please find me a solution to this. Thanks

@Darpan 和 @Fred 是对的.我启用了日志记录以进行改造.就是这么写的

EDIT : @Darpan and @Fred was right. I enabled the logging for retrofit. this is what it says

D/OkHttp: --> POST http://myurl/posts http/1.1
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 26
D/OkHttp: title=vz&body=gde&userId=1
D/OkHttp: --> END POST (26-byte body)
D/OkHttp: <-- 200 OK http://mywebsite/404/
    <html of my 404 page>
D/OkHttp: <-- END HTTP (2119-byte body) 

它给了我服务器的 404.html 文件作为响应.但是当我从 POSTMAN 调用相同的 API 时,它给了我想要的结果.

It's giving me my servers' 404.html file as the response. but When I call the same API from POSTMAN it's giving me the desired result.

所以基本上我可以从 POSTMAN 访问并获取结果,但不能使用改造从 Android 应用程序中使用它

So basically I can access and get the result from POSTMAN but cannot consume it from Android app using retrofit

知道如何解决吗?可能是什么问题?

Any idea how to fix it? what can be the problem?

推荐答案

从你的基本 url http://myurl/v1/

这就是它抛出 404 的原因.

That's why it is throwing 404.

这篇关于Android Retrofit - POST 请求不起作用,但在 Postman 中它起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆