Отправка POST-запроса в Android (Java) с использованием Retrofit, .. работает аналогично следующему коду Python - PullRequest
0 голосов
/ 23 сентября 2018

Мне нужно вызвать API из приложения для Android, но я не могу заставить его работать .. Тот же код py работает нормально .. Как перенести следующий код Python в Android с помощью Retrofit?

import requests
import json

head = {'X-API-KEY':'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
args = {'item1', 'value'}

c = requests.post("http_link",data=json.dumps(args),headers=head)
print(c.text)

Еслирешение доступно без использования библиотеки модернизации, пожалуйста, поделитесь.Я попытался реализовать приведенный выше код Python в приложении, используя библиотеку для модификации следующим образом ... Интерфейс:

public interface Safety_aws_api {
    String BASE_URL = "httplink";
    @Headers("{X-API-KEY:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}")
    @POST("Apisender")
    Call<ModelApiResponse> getApi(@Body Model_ApiCaller model_apiCaller);
}

Классы моделей:

public class Model_ApiCaller {
    public String getApiName() {
        return apiName;
    }

    public void setApiName(String apiName) {
        this.apiName = apiName;
    }

    private String apiName;
    public Model_ApiCaller( String apiName){
        this.apiName = apiName;
    }

    public Model_ApiCaller(){

    }
}


public class ModelApiResponse {
    private String types, Api;

    public String getTypes() {
        return types;
    }

    public void setTypes(String types) {
        this.types = types;
    }

    public String getApi() {
        return Api;
    }

    public void setApi(String api) {
        Api = api;
    }
}

Класс помощника:

 public class RetroHelper {

      private static Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(Safety_aws_api.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

      public static Safety_aws_api api = retrofit.create(Safety_aws_api.class);
}

Функция вызова:

private void getCodes( Model_ApiCaller model_apiCaller) {
    Call<ModelApiResponse> call = RetroHelper.api.getApi(model_apiCaller);
    call.enqueue(new Callback<ModelApiResponse>() {

        @Override
        public void onResponse(Call<ModelApiResponse> call, Response<ModelApiResponse> response) {
            tv_sample_data.setText( response.body().getApi());
        }

        @Override
        public void onFailure(Call<ModelApiResponse> call, Throwable t) {
            Toast.makeText( MainActivity.this, "errr", Toast.LENGTH_SHORT);
            tv_sample_data.setText("erererer");
        }
    });
}

Ответы [ 2 ]

0 голосов
/ 25 сентября 2018

** Интерфейс (изменен, благодаря @Jay за предложение @Header), наконец, добавил тело типа RequestBody, чтобы оно заработало:

public interface Safety_aws_api {
    String BASE_URL = "httplink";
    @POST("Apisender")
    Call<List<ModelApiResponse>> getApi(@Header("x-api-key") String apiKey, @Body RequestBody body);
}

Классы моделей:

public class Model_ApiCaller {
    public String getApiName() {
        return apiName;
    }

    public void setApiName(String apiName) {
        this.apiName = apiName;
    }

    private String apiName;
    public Model_ApiCaller( String apiName){
        this.apiName = apiName;
    }

    public Model_ApiCaller(){

    }
}


public class ModelApiResponse {
    private String types, Api;

    public String getTypes() {
        return types;
    }

    public void setTypes(String types) {
        this.types = types;
    }

    public String getApi() {
        return Api;
    }

    public void setApi(String api) {
        Api = api;
    }
}

Помощниккласс:

 public class RetroHelper {

      private static Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(Safety_aws_api.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

      public static Safety_aws_api api = retrofit.create(Safety_aws_api.class);
}

** Вызывающая функция (изменено «ModelApiResponse» на «List (ModelApiResponse)»):

 private void getCodes( Model_ApiCaller model_apiCaller) {
    MediaType mediaType = MediaType.parse("application/octet-stream");
    RequestBody body = RequestBody.create(mediaType, "{\"types\":\""+ model_apiCaller.getApiName()+"\"}");
    Call<List<ModelApiResponse>> call = null;
    call = RetroHelper.api.getApi("api_key",body);
    call.enqueue(new Callback<List<ModelApiResponse>>() {
        @Override
        public void onResponse(Call<List<ModelApiResponse>> call, Response<List<ModelApiResponse>> response) {
            try {
                tv_sample_data.setText( response.body().get(0).getApi());
            } catch (Exception e) {
                Log.d(TAG, "onResponse: "+e.toString());

            }
            Log.d(TAG, "onResponse: "+response.code());
        }

        @Override
        public void onFailure(Call<List<ModelApiResponse>> call, Throwable t) {
            tv_sample_data.setText("erererer!!!!");
        }
    });
}
0 голосов
/ 23 сентября 2018

Попробуйте добавить заголовок с кодом ниже.Если вывод такой же, пожалуйста, поделитесь своим текущим ответом на вызов API.

   Call<ModelApiResponse> getApi(@Header("X-Authorization") String apiKey,@Body Model_ApiCaller model_apiCaller);
...