简体   繁体   English

使用RetroFit2和Android / Java的首次API调用

[英]First API call using RetroFit2 and Android/Java

I've written an iOS app and a PHP backend. 我已经编写了一个iOS应用程序和一个PHP后端。 Now I want to get started on the Android frontend but I have no idea what I'm doing. 现在,我想开始使用Android前端,但是我不知道自己在做什么。

My project structure looks like this: 我的项目结构如下:

在此处输入图片说明

My ApiClient: 我的ApiClient:

package com.dimsumdev.runk.rest;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {

    public static final String BASE_URL = "http://localhost/index.php/api/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

My ApiInterface: 我的ApiInterface:

package com.dimsumdev.runk.rest;

import com.dimsumdev.runk.model.*;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface ApiInterface {
    @GET("challenge/challenge/id/{id}")
    Call<Challenge> getChallenge(@Path("id") int id);
}

My Challenge model: 我的挑战模型:

package com.dimsumdev.runk.model;

import com.google.gson.annotations.SerializedName;

public class Challenge {
    @SerializedName("challenge_id")
    Integer challengeId;
    @SerializedName("challenge_name")
    String challengeName;
    @SerializedName("challenge_description")
    String challengeDescription;
    @SerializedName("created")
    String created;
    @SerializedName("challenge_status")
    String challengeStatus;
}

And my HomeActivity: 而我的HomeActivity:

package com.dimsumdev.runk.activity;

import android.support.v7.app.AppCompatActivity;
import com.dimsumdev.runk.R;
import com.dimsumdev.runk.model.*;
import android.os.Bundle;
import com.dimsumdev.runk.rest.ApiClient;
import com.dimsumdev.runk.rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends AppCompatActivity {

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

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<Challenge> call = apiService.getChallenge(2);

        call.enqueue(new Callback<Challenge>() {

            @Override
            public void onResponse(Call<Challenge> call, Response<Challenge> response) {
                System.out.print("success");
            }

            @Override
            public void onFailure(Call<Challenge> call, Throwable t) {
                System.out.print("error");
            }
        });
    }
}

The problem is that in the HomeActivity class it keeps running into the error print. 问题是在HomeActivity类中,它一直运行到错误打印中。 This is not what I would expect the program to do. 这不是我希望程序执行的操作。

The backend seems to work fine in Postman: 后端在Postman中似乎工作正常:

在此处输入图片说明

Added this image after adding the Log.d statement in the onFailure() 在onFailure()中添加Log.d语句后添加了此图像

在此处输入图片说明

The defined base url points to localhost, which means it expects that your phone is running your PHP backend. 定义的基本URL指向localhost,这意味着它希望您的电话正在运行PHP后端。

Replace 更换

public static final String BASE_URL = "http://localhost/index.php/api/";

with

public static final String BASE_URL = "http://<<ENTER-YOUR-PHP-BACKEND-MACHINE_IP>>/index.php/api/";

Even if you use a emulator (which is an own virtual device), you can not use localhost. 即使使用仿真器(它是自己的虚拟设备),也不能使用localhost。 You have to enter the IP of your machine. 您必须输入机器的IP。

Use the real server for example i use hostinger which gives free service upload your files and database and then check, it will work. 例如,使用真实的服务器,我使用托管服务,它可以免费提供上传文件和数据库的服务,然后检查是否可以运行。 There is no error in your code 您的代码没有错误

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

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