我的改装回应的内容为null,但适用于Postman

时间:2018-09-02 17:54:00

标签: android retrofit2

我使用WampServer将backend连接到我的android项目,并使用PHP和MySQL。

当我测试与邮递员的请求时,其工作正常,但在android正文中为null。  我的笔记本电脑和移动设备位于同一网络上,Android收到了响应,但正文为null。

我检查response.code()并禁止403;

我是android和PHP的新手,我不知道该如何解决这个问题。

这是我的PHP代码:

<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_POST['userName'])) {
$userName = $_POST['userName'];
$result = mysql_query("SELECT *FROM members WHERE userName =  '$userName'");
if (!empty($result)) {
    if (mysql_num_rows($result) > 0) {
        $response["success"] = 0;
        echo json_encode($response);
    } else {
        $response["success"] = 1;
        echo json_encode($response);
    }
} else {
    $response["success"] = 1;
    echo json_encode($response);
}
     } else {
$response["success"] = 0;
echo json_encode($response);
  }
  ?>

这是我的android api代码:

   @FormUrlEncoded
@POST("project/creataccountusername.php")
Call<createAccountJm> createacountusername(@Field("userName") String userName);

这是我的android模型:

public class createAccountJm {
int success;



public int getSuccess() {
    return success;
}

public void setSuccess(int success) {
    this.success = success;
}
 }



public class CreatAccount extends AppCompatActivity {
private Button next;
private TextInputLayout error;
private TextInputEditText username;
private String name;
private SharedPreferences share;
@Override
protected void onCreate( Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.creataccountpage);
    next=findViewById(R.id.creataccount);
    error=findViewById(R.id.usernameet);
 username=findViewById(R.id.usernameinput);
    share=getSharedPreferences("createAccount",MODE_PRIVATE);
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.3.5/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    final apiInterface service = retrofit.create(apiInterface.class);
 next.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         name=username.getText().toString();
            Call<createAccountJm> call=service.createacountusername(name);
            call.enqueue(new Callback<createAccountJm>() {
                @Override
                public void onResponse(Call<createAccountJm> call, Response<createAccountJm> response) {
                     if(response.body().getSuccess()==1){
                        SharedPreferences.Editor edit =share.edit();
                        edit.putString("username",name);
                        edit.commit();
                        Intent emailpage = new Intent(CreatAccount.this, enteremailpage.class);
                        startActivity(emailpage);
                    }
                    else{
                        error.setError("این نام کاربری در حال حاضر استفاده میشود!");
                    }
                }

                @Override
                public void onFailure(Call<createAccountJm> call, Throwable t) {
   error.setError("اشکال در ارتباط با سرور لطفا مجددا تلاش کنید!");
                }
            });
 });

}

}

这是邮递员的回应:

{
    "success": 1
}

2 个答案:

答案 0 :(得分:0)

解决方案:

代替:

int success;

在您的Model类中,编写以下代码:

@SerializedName("success")
public int success;

就这样,希望对您有所帮助。

如果遇到403禁止错误,请执行以下步骤并尝试:

第1步:

C:\ wamp64 \ bin \ apache \ apache2.4.23 \ conf

第2步:进行更改

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options +Indexes +FollowSymLinks +Multiviews

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   AllowOverride FileInfo AuthConfig Limit
#
AllowOverride all

#
# Controls who can get stuff from this server.
#

#onlineoffline tag - don't remove
Require all granted

编辑不需要要求所有已授予

2)现在转到C:\wamp64\bin\apache\apache2.4.23\conf\extra\httpd-vhost.conf,并对为本地主机定义的虚拟主机进行相同的更改

AllowOverride All
Require all granted

重启服务器,使其正常运行

如果遇到Lenient错误,请尝试:

implementation 'com.google.code.gson:gson:2.6.1'

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

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(insert_your_url)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

请检查。

答案 1 :(得分:0)

您正在使用localhost。因此,尝试在笔记本电脑中运行热点并将移动设备连接到它。

然后将您的笔记本电脑IP放入

        .baseUrl("http://10.0.2.2/")

如果它不起作用,请调试代码并查看logcat以找出问题所在