Android Retrofit-POST请求无效,但在Postman中有效 [英] Android Retrofit - POST request doesn't work, but in Postman it works

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

问题描述

这是我遇到的错误:


com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:
预期为BEGIN_OBJECT,但在第1行第1列的路径STRING处$


我从邮递员得到的JSON响应:

  {
title:测试标题,
body: test body,
userId:1,
id:101
}

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

  $ 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 方法:

 函数echoResponse($ status_code,$ response){
$ app = \Slim\Slim :: getInstance();
$ app-> status($ status_code);
$ app-> contentType('application / json');

echo json_encode($ response);
}

我调用API的方法:

  public void sendPost(String title,String body){
mAPIService.savePost(title,body,1).enqueue(new Callback< Post>( ){
@Override
public void onResponse(Call< Post>呼叫,Response< Post>响应){
Log.i(TAG,将sendPost发送到onResponse。);
if(response.isSuccessful()){
showResponse(response.body()。toString());
Log.i(TAG,帖子已提交至API。 + response.body( ).toString());
}
}

@Override
public void onFailure(Call< Post> call,Throwable t){
日志.e(TAG,无法将帖子提交到API。);
Log.e(TAG,t.toString());
}
});
}

APIServie 接口:

 公共接口APIService {
@POST( / posts)
@FormUrlEncoded
呼叫< Post> savePost(@Field( title)字符串标题,
@Field( body)字符串主体,
@Field( userId)long userId);
}

我如何获得改造实例:

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

公共静态APIService getAPIService(){
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}

}
公共类RetrofitClient {
private static Retrofit Retrofit = null;

私有静态Gson gson = new GsonBuilder()
.setLenient()
.create();

公共静态Retrofit getClient(String baseUrl){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
退货改造;
}
}

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



编辑:
@Darpan和@Fred是正确的。我启用了日志记录以进行改进。这就是它的意思

  D / OkHttp:-> POST http:// myurl / posts http / 1.1 
D / OkHttp:内容类型:application / x-www-form-urlencoded
D / OkHttp:内容长度:26
D / OkHttp:title = vz& body = gde& userId = 1
D / OkHttp:-> END POST(26位元组)
D / OkHttp:<-200 OK http:// mywebsite / 404 /
< html of my 404 page>
D / OkHttp:<-END HTTP(2119字节的正文)

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



因此,基本上,我可以从POSTMAN访问并获取结果,但无法使用改造



任何想法如何解决?
可能是什么问题?

解决方案

删除最后一个 / 来自您的基本URL http:// myurl / v1 /



这就是为什么它会抛出404。 / p>

This is the error I'm getting:

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

JSON response I'm getting from Postman:

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

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 method:

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

    echo json_encode($response);
}

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());
        }
    });
}

The APIServie interface:

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

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;
   }
}

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

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) 

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.

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?

解决方案

Remove the last / from your base url http://myurl/v1/

That's why it is throwing 404.

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

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