为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Retrofit 在 Android ( Java) 中发送 POST 请求

使用 Retrofit 在 Android ( Java) 中发送 POST 请求

紫衣仙女 2021-10-06 12:59:52
我需要从 android 应用程序调用一个 API,但不能让它工作.. 相同的 py 代码工作正常.. 如何使用 Retrofit 在 Android 中移植以下 python 代码?import requestsimport jsonhead = {'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());        }
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

尝试使用以下代码添加标题。如果输出相同,请分享您当前对 API 调用的响应。

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



查看完整回答
反对 回复 2021-10-06
  • 2 回答
  • 0 关注
  • 397 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信