在Android Studio中使用Retrofit进行GET请求的问题 [英] Issues with GET request using Retrofit in android studio

查看:235
本文介绍了在Android Studio中使用Retrofit进行GET请求的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Android Studio中使用Retrofit 2从CUMTD api获取JSON形式的停止信息以通过搜索来停止,并且由于某种原因,连接持续失败,查询参数和其他所有内容都正确,我习惯了从JSON到模型类的p​​ojo转换器,所以它应该是正确的,或者是来自主要活动的东西?这是我要连接到的URL

I'm using Retrofit 2 in Android Studio to get stop information in JSON form from the CUMTD api for stops by search and for some reason the connection keeps on failing, are the query parameters and everything else correct, i used to the JSON to pojo converter for the model class so it should be correct or is it something from main activity? Heres the URL I'm trying to connect to https://developer.cumtd.com/api/v2.2/json/GetStopsBySearch?key=b7cd7d8c64b24b4f8415aeb57d6f7f74&query=transit%20plaza my code:

    import java.util.List;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Example {

        @SerializedName("changeset_id")
        @Expose
        private String changesetId;
        @SerializedName("new_changeset")
        @Expose
        private Boolean newChangeset;
        @SerializedName("time")
        @Expose
        private String time;
        @SerializedName("status")
        @Expose
        private Status status;
        @SerializedName("rqst")
        @Expose
        private Rqst rqst;
        @SerializedName("stops")
        @Expose
        private List<Stop> stops = null;

        public String getChangesetId() {
            return changesetId;
        }

        public void setChangesetId(String changesetId) {
            this.changesetId = changesetId;
        }

        public Boolean getNewChangeset() {
            return newChangeset;
        }

        public void setNewChangeset(Boolean newChangeset) {
            this.newChangeset = newChangeset;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public Status getStatus() {
            return status;
        }

        public void setStatus(Status status) {
            this.status = status;
        }

        public Rqst getRqst() {
            return rqst;
        }

        public void setRqst(Rqst rqst) {
            this.rqst = rqst;
        }

        public List<Stop> getStops() {
            return stops;
        }

        public void setStops(List<Stop> stops) {
            this.stops = stops;
        }

    }




    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    import java.util.List;
    import java.util.Random;

    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;

    import static android.R.attr.x;
    import static android.media.CamcorderProfile.get;
    import static com.example.neelpatel.weatherapp.MTDApi.retrofit;

    public class MainActivity extends AppCompatActivity {

        String key= "b7cd7d8c64b24b4f8415aeb57d6f7f74";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);//Starts Retrofit
            final MTDApi mtdApi = MTDApi.retrofit.create(MTDApi.class);

            //Sets up Button and EditText for use in this class
            final EditText edit = (EditText) findViewById(R.id.edit);
            Button requestButton = (Button) findViewById(R.id.button);

            //Behavior once button is clicked
            requestButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String s = edit.getText().toString();
                    //Sets up up the API call
                    Call<List<Example>> call = mtdApi.loadStops(key,s);

                    //Runs the call on a different thread
                    call.enqueue(new Callback<List<Example>>() {
                        @Override
                        //Once the call has finished

                        public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {
                            if (response.isSuccessful()) {
                                //Gets the list of stops
                                List<Example> stops = response.body();
                                List<Stop> list = stops.get(0).getStops();
                                String text = list.get(0).getStopId();
                                edit.setText(text);
                            } else {
                                // show error message
                                Log.e("RequestCall", "Request failed");
                            }
                        }

                        @Override
                        //If the call failed
                        public void onFailure(Call<List<Example>> call, Throwable t) {
                            edit.setText("Request Failed");
                            Log.e("RequestCall", "Request failed");
                        }
                    });
                }
            });
        }
    }







        import java.util.List;

        import retrofit2.Call;
        import retrofit2.Retrofit;
        import retrofit2.converter.gson.GsonConverterFactory;
        import retrofit2.http.GET;
        import retrofit2.http.Path;
        import retrofit2.http.Query;

        /**
         * Class that details the request(s) that we will call
         */

        public interface MTDApi{
            @GET("GetStopsBySearch")
            Call<List<Example>> loadStops(@Query("key") String key,
            @Query("query") String query);
            Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://developer.cumtd.com/api/v2.2/json/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    }


    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Params {

        @SerializedName("count")
        @Expose
        private Integer count;
        @SerializedName("query")
        @Expose
        private String query;

        public Integer getCount() {
            return count;
        }

        public void setCount(Integer count) {
            this.count = count;
        }

        public String getQuery() {
            return query;
        }

        public void setQuery(String query) {
            this.query = query;
        }

    }


    import com.example.neelpatel.weatherapp.Params;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Rqst {

        @SerializedName("method")
        @Expose
        private String method;
        @SerializedName("params")
        @Expose
        private Params params;

        public String getMethod() {
            return method;
        }

        public void setMethod(String method) {
            this.method = method;
        }

        public Params getParams() {
            return params;
        }

        public void setParams(Params params) {
            this.params = params;
        }

    }


    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Status {

        @SerializedName("code")
        @Expose
        private Integer code;
        @SerializedName("msg")
        @Expose
        private String msg;

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

    }



    import java.util.List;

    import com.example.neelpatel.weatherapp.StopPoint;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Stop {

        @SerializedName("stop_id")
        @Expose
        private String stopId;
        @SerializedName("stop_name")
        @Expose
        private String stopName;
        @SerializedName("code")
        @Expose
        private String code;
        @SerializedName("percent_match")
        @Expose
        private Integer percentMatch;
        @SerializedName("stop_points")
        @Expose
        private List<StopPoint> stopPoints = null;

        public String getStopId() {
            return stopId;
        }

        public void setStopId(String stopId) {
            this.stopId = stopId;
        }

        public String getStopName() {
            return stopName;
        }

        public void setStopName(String stopName) {
            this.stopName = stopName;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public Integer getPercentMatch() {
            return percentMatch;
        }

        public void setPercentMatch(Integer percentMatch) {
            this.percentMatch = percentMatch;
        }

        public List<StopPoint> getStopPoints() {
            return stopPoints;
        }

        public void setStopPoints(List<StopPoint> stopPoints) {
            this.stopPoints = stopPoints;
        }

    }


    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class StopPoint {

        @SerializedName("code")
        @Expose
        private String code;
        @SerializedName("stop_id")
        @Expose
        private String stopId;
        @SerializedName("stop_lat")
        @Expose
        private Double stopLat;
        @SerializedName("stop_lon")
        @Expose
        private Double stopLon;
        @SerializedName("stop_name")
        @Expose
        private String stopName;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getStopId() {
            return stopId;
        }

        public void setStopId(String stopId) {
            this.stopId = stopId;
        }

        public Double getStopLat() {
            return stopLat;
        }

        public void setStopLat(Double stopLat) {
            this.stopLat = stopLat;
        }

        public Double getStopLon() {
            return stopLon;
        }

        public void setStopLon(Double stopLon) {
            this.stopLon = stopLon;
        }

        public String getStopName() {
            return stopName;
        }

        public void setStopName(String stopName) {
            this.stopName = stopName;
        }

    }

推荐答案

您没有提供有关故障本身的太多(任何)信息,但是很容易发现至少一个可能的错误.在响应中,您希望有个对象的 list :

You didn't provide much (any) information about the failure itself, but it's pretty easy to spot at least one possible bug. In the response you expect a list of Example objects:

Call<List<Example>> call = mtdApi.loadStops(key,s);

这不好,因为您可以在 GetStopsBySearch 返回的JSON对象不是列表(即,不是JSON数组).解决这个问题确实很容易,只需要一个Example对象而不是其中的一个列表即可:

This is not good since you can cleary see in the documentation of GetStopsBySearch that the returned JSON object is not a list (i.e. not a JSON array). Fixing this is really easy, just expect a single Example object instead of a list of those:

Call<Example> call = mtdApi.loadStops(key,s);

这显然意味着您必须更改Callback的签名,但是您不需要其他信息.

This obviously means that you have to change the signature of the Callback but you don't need extra info for that.

这篇关于在Android Studio中使用Retrofit进行GET请求的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆