简体   繁体   中英

Response Message-Not Found and Response code-404 while calling the api in retrofit

Webservice to fetch data from database is as given below:

Smart.php

define('HOST','localhost');
        define('USER','root');
        define('PASS','root');
        define('DB','Stud');

      $con = mysqli_connect(HOST,USER,PASS,DB);

      $sql = "select * from Student";

       $result=array();

      $res = mysqli_query($con,$sql);

        enter code here

      while($row = mysqli_fetch_array($res)){
        array_push($result,
        array('id'=>$row[0],
        'name'=>$row[1],
        'address'=>$row[2]
      ));
    }
    echo json_encode(array("result"=>$result));

    mysqli_close($con);


?>

Android program is as given below:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    public static final String BASE_URL = "http://localhost:80/Projecr/";

    ApiServices as;

    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView)findViewById(R.id.text);
        Button btn=(Button)findViewById(R.id.btn);

        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl(BASE_URL)

                .addConverterFactory(GsonConverterFactory.create())

                .build();
        as=retrofit.create(ApiServices.class);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                load();
            }
        });

    }
    private void load() {
        try {
            Call<Example> call = as.List();

            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Call<Example> call, Response<Example> response) {
                    //      int statusCode = response.code();
                    if(!response.isSuccessful())
                    {
                        Log.e("API not success",response.toString()+response.message()+response.errorBody()+response.code());
                    }
                    Example e = response.body();
                    if (e == null) {
                        Toast.makeText(getApplicationContext(), "Null", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Not Null", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Call<Example> call, Throwable t) {
                    Log.e("Failed","t.printStackTrace()"+t.getCause()+t.getMessage());
                    tv.setText("Failure");
                }
            });
        }
        catch (Exception e)
        {
            String TAG="tag";
            Log.e(TAG, e.getMessage());
        }
    }
}

Example.java

public class Example {

    @SerializedName("result")
    @Expose
    private List<Result> result = null;

    public List<Result> getResult() {
        return result;
    }

    public void setResult(List<Result> result) {
        this.result = result;
    }

}

Result.java

public class Result {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("address")
    @Expose
    private String address;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

ApiServices.java Interface

public interface ApiServices {

    @GET("Smart.php")
    Call<Example> List();

}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.saloni.retrofit_sample.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:id="@+id/text" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    android:text="click"
    />
</LinearLayout>

When I run this program, on clicking button, I get the toast null and the logcat output is as follows:

E/API not success: retrofit2.Response@d45de1e Not Found okhttp3.ResponseBody$1@9a0e6ff 404

Which means that the response message is "Not Found" and response code is "404".

After editing the program as suggested and removing "/" ,it gives following error in logcat:

E/Failed: t.printStackTrace()java.lang.UnsupportedOperationException: Interface can't be instantiated! Interface name: javax.xml.transform.ResultUnable to invoke no-args constructor for interface javax.xml.transform.Result. Register an InstanceCreator with Gson for this type may fix this problem.

public interface ApiServices {

@GET("/Smart.php")
Call<List<Result>> List();

}

instead of

public interface ApiServices {

@GET("Smart.php")
Call<List<Result>> List();

}

I solved this error successfully without any further errors. My Result.java class conflicted with javax.xml.transform.Result class . so i renamed my Result.java class

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