简体   繁体   English

在改造中调用api时未找到响应消息和响应代码404

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

Webservice to fetch data from database is as given below: 从数据库中获取数据的Web服务如下所示:

Smart.php 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: Android程序如下:

MainActivity.java 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 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 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 ApiServices.java接口

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: 当我运行该程序时,在单击按钮时,我得到了Toast null,logcat输出如下:

E/API not success: retrofit2.Response@d45de1e Not Found okhttp3.ResponseBody$1@9a0e6ff 404 E / API不成功:Retrofit2.Response@d45de1e找不到okhttp3.ResponseBody$1@9a0e6ff 404

Which means that the response message is "Not Found" and response code is "404". 这意味着响应消息为“未找到”,响应代码为“ 404”。

After editing the program as suggested and removing "/" ,it gives following error in logcat: 按照建议编辑程序并删除“ /”后,在logcat中给出以下错误:

E/Failed: t.printStackTrace()java.lang.UnsupportedOperationException: Interface can't be instantiated! E /失败:t.printStackTrace()java.lang.UnsupportedOperationException:接口无法实例化! Interface name: javax.xml.transform.ResultUnable to invoke no-args constructor for interface javax.xml.transform.Result. 接口名称:javax.xml.transform.Result无法为接口javax.xml.transform.Result调用no-args构造函数。 Register an InstanceCreator with Gson for this type may fix this problem. 使用此类型向Gson注册InstanceCreator可能会解决此问题。

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 . 我的Result.java类与javax.xml.transform.Result类冲突。 so i renamed my Result.java class 所以我重命名了Result.java类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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