Android最火的获得网络请求框架Retrofit的简单GET、POST请求使用

首先,在Manifest添加依赖库

    // Retrofit库
    implementation  'com.squareup.retrofit2:retrofit:2.0.2'
    // Okhttp库
    implementation  'com.squareup.okhttp3:okhttp:3.10.0'
    //json
    implementation  'com.squareup.retrofit2:converter-gson:2.0.2'

首先是GET方法,向服务器发起数据请求,获取信息。类似于数据库的select操作,只是查询,不会影响资源的内容。@Path请求参数直接跟在请求路径下,比如请求网址为login/sendMessage/18888888888

    @GET("login/sendMessage/{phone}")
    Call<ResponseResult> sendMessage(@Path("phone") String phone);
    public void request() {
        //创建Retrofit对象
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl("http://192.168.10.212:8311/salary/center/")//设置网络请求URL
                .addConverterFactory(GsonConverterFactory.create())//设置使用Gson解析
                .build();
        //创建网络接口请求的实例
        IGetRequest getRequest = retrofit.create(IGetRequest.class);
        //对发送请求进行封装
        Call<ResponseResult> call = getRequest.sendMessage("18332700757");
        //发送网络请求
        call.enqueue(new Callback<ResponseResult>() {
            //请求成功的回调
            @Override
            public void onResponse(Call<ResponseResult> call, Response<ResponseResult> response) {
                //JsonHelper是自己封装的Json对Object的转化方法
                SendMessageResult sendMessageResult = JsonHelper.jsonToObject(response.body().getResult().toString(),SendMessageResult.class);
                System.out.println(sendMessageResult != null ? sendMessageResult.getPhone() : null);
                System.out.println(sendMessageResult != null ? sendMessageResult.getVrtifcation() : null);
            }

            //请求失败时的回调
            @Override
            public void onFailure(Call<ResponseResult> call, Throwable t) {
                System.out.println("连接失败");
            }
        });
    }

POST请求一般带着参数body类,
body参数:{“phone”:“18888888888”,“password”:“123456”}
这里有三种写法

    @POST("login/login")
    Call<ResponseResult> login(@Body LoginParam param);
    Call<ResponseResult> login(@Field("phone")String phone, @Field("password")String password);
    Call<ResponseResult> login(@FieldMap Map<String, String> paramsMap);
       HashMap<String, String> hashMap = new HashMap<>();
       hashMap.put("phone","18888888888");
       hashMap.put("password","123456");

    public void postRequest() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.10.212:8311/salary/center/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //创建网络接口请求的实例
        IGetRequest getRequest = retrofit.create(IGetRequest.class);
        //对 发送请求进行封装
        LoginParam loginParam = new LoginParam();
        loginParam.setPhone("18332700757");
        loginParam.setPassword("123456");
        Call<ResponseResult> call = getRequest.login(loginParam);
        call.enqueue(new Callback<ResponseResult>() {
            @Override
            public void onResponse(Call<ResponseResult> call, Response<ResponseResult> response) {
                LoginResult loginResult = JsonHelper.jsonToObject(response.body().getResult().toString(),LoginResult.class);
                System.out.println(loginResult.getToken());
            }

            @Override
            public void onFailure(Call<ResponseResult> call, Throwable t) {
                System.out.println("请求失败");
                System.out.println(t.getMessage());
            }
        });
    }

POST、GET代码在一个抽象类中

package com.example.retrofit;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;

/**
 * @Author WF
 * @createTime 2019/4/21
 */
public interface IGetRequest {
    @GET("login/sendMessage/{phone}")
    Call<ResponseResult> sendMessage(@Path("phone") String phone);

    @POST("login/login")
    Call<ResponseResult> login(@Body LoginParam param);
}

下面是返回值的类

package com.example.retrofit;

/**
 * @Author WF
 * @createTime 2019/4/21
 */
public class ResponseResult<T> {
    private String statusCode;
    private String message;
    private T result;

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String getMessage() {
        return message;
    }

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

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }
}

package com.example.retrofit;

/**
 * @Author WF
 * @createTime 2019/4/21
 */
public class SendMessageResult {
    private String phone;
    private String vrtifcation;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getVrtifcation() {
        return vrtifcation;
    }

    public void setVrtifcation(String vrtifcation) {
        this.vrtifcation = vrtifcation;
    }
}

package com.example.retrofit;

/**
 * @Author WF
 * @createTime 2019/4/21
 */
public class LoginResult {
    private String token;
    private String phone;
    private String userName;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getUserName() {
        return userName;
    }

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

参数类

package com.example.retrofit;

/**
 * @Author WF
 * @createTime 2019/4/21
 */
public class LoginParam {
    private String phone;

    private String password;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

输出为

04-21 15:14:58.222 3519-3519/com.example.retrofit I/System.out: 00f9f2e4-e1bb-4fd5-8f53-8c6ec7d49d09
04-21 15:14:58.223 3519-3519/com.example.retrofit I/System.out: 18332700757
04-21 15:14:58.223 3519-3519/com.example.retrofit I/System.out: 3020
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值