在Android上调用POST API [英] Calling a POST API on android

查看:228
本文介绍了在Android上调用POST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Android请求一个简单的POST-API,该API会使用一个简单的JSON对象进行响应.

From Android, I'm trying to request a simple POST-API that responses with a simple JSON object.

说,我有一个简单的API(1.1.1.1/testApi),该API响应包含以下内容的JSON对象:

Say, I have a simple API (1.1.1.1/testApi) that respons with a JSON object that contains:

  • 状态:状态值
  • 名称:名称值

使用Postman调用API 就像一个魅力,所以我认为我的API很好.

Calling the API using Postman works like a charm, so I assume that my API was fine.

我已经尝试了以下一些链接:

I already tried some of the links below:

  1. AsyncTask :没有关于如何调用CallApi对象的示例并解析API地址(例如URL),因此在尝试调用该对象时始终会出错.
  2. Apache HTTP客户端:正如链接所说,几乎所有答案都是Android 6.0不推荐使用
  3. 改造:似乎可用,但我找不到合适的示例在我的计算机上使用它情况
  1. AsyncTask: there is no example on how to call the CallApi object and parse the API address (e.g. URL), so there is always an error when I try to invoke the object.
  2. Apache HTTP Client: as the link said, nearly all of the answer are deprecated for Android 6.0
  3. Retrofit: seems usable, but I can't find a proper example to use this in my case

我确实花了一些时间来搜索有关此问题的解决方案,但是afaik没有调用POST-API的简便"方法.

I did take my time to search solutions regarding this, but afaik there is no "easy" way to call a POST-API.

有没有简单的方法需要输入URL,然后返回JSON对象?

Is there any simple method that takes an URL input, then returns a JSON object?

让我知道这是否是重复的问题.

Let me know if this was a duplicated question.

谢谢.

推荐答案

您好,我正在使用改造示例,您可以按照自己的方式进行尝试

Hello I Have working Retrofit Example try it on your manner

开始吧

1)成绩

    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.1' 

2)接口

public interface ServiceInterface {
@GET(HttpConstants.USERDATAJSON)
    Call<ListData>taskData(@Query("method")String method,@Query("stdID")int stdID);
}

3)服务等级

public class ServiceClass {
    static ServiceInterface serviceInterface;
//    public static final String baseUrl= HttpConstants.BASE_URL_GEONAME;
    public static final String baseUrl= HttpConstants.baseUrl;

    public static ServiceInterface connection(){
        if(serviceInterface==null){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient();
            client.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response response=chain.proceed(chain.request());
                    return response;
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(baseUrl)
                    .build();
            serviceInterface=retrofit.create(ServiceInterface.class);
        }
        return serviceInterface;
    }
}

4)从活动中调用方法

public void getTaskData(){
        ServiceInterface serviceInterface=ServiceClass.connection();
        Call<ListData> call=serviceInterface.taskData("getAllUsersSimple",0);
        call.enqueue(new Callback<ListData>() {
            @Override
            public void onResponse(Response<ListData> response, Retrofit retrofit) {
                Log.v("@@@Response",""+response.toString());
                if(response.isSuccess()){
                    listData=response.body();
                    dataList=listData.getData();
                    printStudentDetails(dataList);

                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.v("@@@Failure"," Message"+t.getMessage());
            }
        });
    }

5) The Pojo

public class ListData {

    @SerializedName("data")
    @Expose
    private List<DataPojo> data = null;
    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;

    public List<DataPojo> getData() {
        return data;
    }

    public void setData(List<DataPojo> data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
public class DataPojo {

    @SerializedName("user_id")
    @Expose
    private String userId;
    @SerializedName("user_name")
    @Expose
    private String userName;
    @SerializedName("user_age")
    @Expose
    private String userAge;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

}

您可以使用此链接创建pojo http://www.jsonschema2pojo.org/

You can create your pojo using this link http://www.jsonschema2pojo.org/

有关更多参考,请访问链接 https://github.com/pratikvyas1991/NetworkingExample/tree/master/app

For more reference visit the link https://github.com/pratikvyas1991/NetworkingExample/tree/master/app

这篇关于在Android上调用POST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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