【问题标题】:No clue why doesn't the code lead to a response, always fails不知道为什么代码不会导致响应,总是失败
【发布时间】:2019-04-17 07:42:32
【问题描述】:

我正在创建这个应用程序,它从 JSON 文件中获取“总线”对象并使用 id 显示其信息。问题是我按照教程并按照我在帖子和视频中看到的那样做了所有事情,但该应用程序总是无法获得响应。我错过了什么?

我正在开发 Android Studio,其中包含 retrofit2 和 gson-converter 所需的 gradle 文件。我创建了 API 接口、Retrofit 创建者类和 ServiceApi 生成器类。还为将获取 json 数据的类制作了 @SerializedName 注释。不过,不知道为什么它不起作用。

JSON:

{
    "response_code":5,
    "response_msg":"Success",
    "bus":{
        "vehicle_id":"1",
        "vehicle_plate":"ا ا ا 4389",
        "category":"ورشة",
        "category_id":2,
        "last_seen":"2019-04-15T12:19:24.4223277",
        "location":{
            "lat":0.0,
            "lon":0.0
        },
        "status":{
            "sos":false,
            "ignition":"",
            "movement":false,
            "speed":0.0
        },
            "driver":{
                "driver_id":0,
                "driver_name":""
            },
            "inspection_report":[]
        }
}

这里是 MainActivity.java(现在只是测试“成功”或“失败”,但它总是给我失败):

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ApiGenerator.getServiceApi().getBusStatus("1").enqueue(new Callback<BusStatus>() {
            @Override
            public void onResponse(Call<BusStatus> call, Response<BusStatus> response) {
                Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<BusStatus> call, Throwable t) {
                Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

这里是 BusStatus.java,它将获取 json 数据:

public class BusStatus {

    @SerializedName("response_code")
    private Integer response_code;
    @SerializedName("response_msg")
    private String response_msg;
    @SerializedName("bus")
    private Bus bus;

    public BusStatus(int response_code, String response_msg, Bus bus) {
        this.response_code = response_code;
        this.response_msg = response_msg;
        this.bus = bus;
    }

    public Integer getResponse_code() {
        return response_code;
    }

    public void setResponse_code(Integer response_code) {
        this.response_code = response_code;
    }

    public String getResponse_msg() {
        return response_msg;
    }

    public void setResponse_msg(String response_msg) {
        this.response_msg = response_msg;
    }

    public Bus getBus() {
        return bus;
    }

    public void setBus(Bus bus) {
        this.bus = bus;
    }
}

Interface MyApi.java(不确定我是否以正确的方式编写查询):

public interface MyApi {



    @GET("/*API PATH*/")
    Call<BusStatus> getBusStatus(@Query("id") String vehicle_id);

}

RetrofitClient 创建者,RetrofitClientInstance:

public class RetrofitClientInstance {

    private static Retrofit retrofit;

    public static Retrofit getRetrofitInstance(){
        Gson gson = new GsonBuilder().setLenient().create();
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(/*BASE URL*/)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

}

API 生成器,ApiGenerator.java:

public class ApiGenerator {

    public static MyApi getServiceApi(){
        return RetrofitClientInstance.getRetrofitInstance().create(MyApi.class);
    }

}

我还确保我在 AndroidManifest.xml 中添加了互联网权限(不要介意其他内容):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testgettingdata">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我现在想要的是成功,所以我可以继续,但不知道为什么会失败,即使我尝试调试但无法理解是什么导致它直接失败。 如果我的代码有错误,请指导我。

编辑:这是我收到 Throwable t 消息时得到的错误: “java.net.UknownServiceExeption:网络安全策略不允许与(/基本 url/)进行 CLEARTEXT 通信”

【问题讨论】:

  • 你能贴出失败原因的详细日志吗?
  • 我的意思是它转到'onFailure'方法,所以我猜没有连接到文件或类似的东西。
  • 检查日志错误肯定有一些错误。 ThrowableonFailure 的一部分,所以使用 t.printStacktrace() 在日志中打印错误。此外,您不能只确定 onSuccess 内的 API 调用成功。您需要使用response.isSuccessful() 来检查这个或HttpStatus Code 也就是resonse.code()
  • @Jian Astrero 结果还是一样,没有回应。

标签: android json api retrofit2


【解决方案1】:

我认为您使用的是 Android Pie,这就是您遇到此问题的原因。这是因为,如文档中所述:

从 Android 9(API 级别 28)开始,明文支持被禁用 默认情况下。

您可以从here 进一步了解这种情况,或者您可以继续添加 usesCleartextTraffic 作为应用程序标签的属性。

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

【讨论】:

  • 谢谢老兄,没错。我按照你说的做了,效果很好。
  • 很高兴为您提供帮助
【解决方案2】:

您必须将您的基本网址更改为:-

http://(BASE URL)/api/

在 inetrface 中是这样的:-

@GET("(API PATH)?")
Call<BusStatus> getBusStatus(@Query("id") String vehicle_id);

【讨论】:

  • 将 http 更改为 https 到您的基本 url
  • 我正在我的应用中尝试这个,然后我会回复你的答案,请稍候
  • chnage @Query("id") String vehicle_id to @Path("id") String vehicle_id
  • 执行此操作,否则我正在处理它,如果有效,请发表评论
  • 它不起作用,我猜@Path 是用于类似目录的东西。我在等你的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2017-04-24
  • 2014-04-08
  • 2020-01-04
  • 1970-01-01
相关资源
最近更新 更多