简体   繁体   中英

Body of my retrofit response is null but it works on Postman

I use WampServer for connect backEnd to my android project and I use PHP and MySQL.

When I test my request with postman is works correctly but in android body of response is null. my laptop and mobile are on the same network and response received by android but body is null.

i check response.code() and it's 403 forbidden;

I am new in android and PHP and I don't know how can I fix this problem.

This is my PHP code:

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

and this is my android api code:

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

This is my android model:

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("اشکال در ارتباط با سرور لطفا مجددا تلاش کنید!");
                }
            });
 });

}

}

it is response in postman:

{
    "success": 1
}

Solution:

Instead of:

int success;

in your Model class, write this:

@SerializedName("success")
public int success;

That's it, Hope it helps.

If you're getting a 403 forbidden error, do the following steps and try:

Step 1:

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

Step 2: Make these changes

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

Edit Require none to Require all granted

2) Now go to C:\\wamp64\\bin\\apache\\apache2.4.23\\conf\\extra\\httpd-vhost.conf and do the same change to the Virtual Host defined for localhost

AllowOverride All
Require all granted

Restart the server it should work

If you are getting Lenient error, then try:

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

Check please.

you are using localhost. so, try to run hotspot in your laptop and connect the mobile to it.

and put your laptop ip in

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

if it does not work, debug your code and see the logcat to figure out the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM