【问题标题】:Expected BEGIN_OBJECT but预期 BEGIN_OBJECT 但
【发布时间】:2018-12-14 05:25:50
【问题描述】:

我在 Android Studio 的 Retrofit 库中工作时遇到了一个大问题, 当我创建一个 PHP 文件以获取某些内容或将某些内容发布到数据库并处理从 API 返回的 JSON 时,当我使用 localhost 时一切正常,但是当我将该 PHP 文件上传到真实主机时,我在 Android Studio 中收到此错误:

预期为 BEGIN_OBJECT,但在第 1 行第 1 列为 STRING

例如:

这是我的界面:

@FormUrlEncoded
@POST("checkuser.php")
Call<chechExistsUser> checkUserExists(@Field("phone") String phone);

这是改造类:

public class Retrofit_Tools {
    private static Retrofit retrofit = null;

    public static Retrofit getRetrofit(String baseUrl) {

        if (retrofit==null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                            .setLenient()
                            .create()))
            .build();
        }
        return retrofit;


    }
}

这是我在任何活动类中获得的通用类:

public class Common {
    private static final String baseUrl="http://192.168.56.1/drinkshop1/";
    //private static final String baseUrl="http://reza-ghahremani.zili.ir/drinkshop/";


    public static Retrifit_Interface getApi(){
        return Retrofit_Tools.getRetrofit(baseUrl).create(Retrifit_Interface.class);
    }
}

我在任何活动中都使用此代码:

Retrifit_Interface retrofit=Common.getApi();

终于我可以在接口中使用任何方法了:

retrofit.checkUserExists(etPhone.getText().toString().trim()).enqueue(new Callback<chechExistsUser>() {
            @Override
            public void onResponse(Call<chechExistsUser> call, Response<chechExistsUser> response) {
                Toast.makeText(MainActivity.this, "" + response.body().error_message, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<chechExistsUser> call, Throwable t) {
                Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_LONG).show();
                return;

            }
        });

如果问题是关于 PHP 文件或 API,为什么在 localhost 中一切正常? 为什么在 localhost 中一切正常,而在 realhost 中却不行?

【问题讨论】:

  • 你需要发布你的代码。
  • localHost 一切正常
  • 你在本地和服务器上运行相同版本的 PHP 吗?
  • 我怎样才能找到它?
  • 使用phpversion()函数。

标签: php android-studio localhost retrofit2


【解决方案1】:

几周前,一位朋友遇到了一个非常相似的问题如果不一样。我们发现 Retrofit 需要一个方括号来包围 json。例如这样的json:

{  
  "data":{  
     "info1":"something here"
    }
}

应该转换成这个:

[{
  "data":{  
    "info1":"something here"
 }
}]

也许这可以解决你的问题

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2019-05-10
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2020-02-10
    • 2015-11-26
    相关资源
    最近更新 更多