预期为BEGIN_OBJECT,但

时间:2018-07-05 16:34:17

标签: php android-studio localhost retrofit2

我在Android Studio的Retrofit Library中遇到很大的问题, 当我创建一个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中一切正常,而在rea​​lhost中不起作用?

1 个答案:

答案 0 :(得分:0)

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

 E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method 
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
  E/dalvikvm: Could not find class 
'android.support.v4.widget.DrawerLayout$1', referenced from method 
android.support.v4.widget.DrawerLayout.<init>
 E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced 
from method android.support.v4.widget.DrawerLayout.onDraw
 E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced 
from method android.support.v4.widget.DrawerLayout.onMeasure
E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.widget.DrawerLayout.onMeasure

应转换为此:

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

也许这可以解决您的问题