Retrofit http 请求

https://www.jianshu.com/p/1fb294ec7e3b

http://square.github.io/retrofit/

可以参考这2篇文章:

公司年会抽奖的:

接口:获取服务器的状态(用于判断是否可以开始抽奖)
url:http://192.168.16.105:8080/getServerStatus
method: Get
success: {"id":1,"start":0,"code":3}
error: {"code":-1,"error":"失败原因"}
id: 可以不用管
start: start=1时可以开始抽奖,为0时不能抽奖
code : 这个代表是第几轮抽奖


接口:将分数上传到服务器
url:http://192.168.16.105:8080/uploadData
method: post
body: {"name":"zhangsan","score":"12"}
success: {"code":0}
error: {"code":-1,"error":"失败原因"}

name: 姓名
score: 分数,1-10

name: 姓名
score: 分数,1-10

Retrofit retrofit = new Retrofit.Builder()
    .addConverterFactory(GsonConverterFactory.create())
    .baseUrl("http://192.168.16.105:8080/")
    .build();

/**
 * get请求
 *
 */
HotRest service = retrofit.create(HotRest.class);
Call<Success> call = service.getHot();
call.enqueue(new Callback<Success>() {
    @Override
    public void onResponse(Call<Success> call, Response<Success> response) {
        Toast.makeText(LoginActivity.this,"Success", Toast.LENGTH_LONG).show();
        //请求成功操作

        Success  success=response.body();
        Log.i("------",response.toString()+"===="+response.body()+"==error=="+success.error+"==code=="+success.code+"==id=="+success.id);
    }
    @Override
    public void onFailure(Call<Success> call, Throwable t) {
        //请求失败操作
        Toast.makeText(LoginActivity.this,"Throwable",Toast.LENGTH_LONG).show();
        Log.i("------",t.toString()+"====");
    }
});



/**
 *   post请求
 */
HotRestPost servicePost = retrofit.create(HotRestPost.class);
JSONObject jsonObject=new JSONObject();
jsonObject.put("name","理解");
jsonObject.put("score","8");
Call<Success>  successCall=servicePost.PostHot(jsonObject);
successCall.enqueue(new Callback<Success>() {
    @Override
    public void onResponse(Call<Success> call, Response<Success> response) {
        Success  success=response.body();
        Log.i("--post----",response.toString()+"===="+response.body()+"==error=="+success.error+"==code=="+success.code+"==id=="+success.id);
    }

    @Override
    public void onFailure(Call<Success> call, Throwable t) {
        Log.i("---post---",t.toString()+"====");
    }
});
public interface HotRestPost {
    @POST("uploadData")
    Call<Success> PostHot(@Body JSONObject jsonObject);
}
public interface HotRest {

    @GET("getServerStatus")
    Call<Success> getHot();
}
public class Success {
    public int id;
    public int start;
    public int code;
    public String error;
}
Retrofit:中要用到的包
compile 'io.reactivex:rxjava:x.y.z'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

由于用到了Post请求,使用了JsonObject传递数据,所以导入:
 
 
compile 'com.alibaba:fastjson:1.1.56.android'
代码很low,仅供参考。 

猜你喜欢

转载自blog.csdn.net/duanjie924/article/details/80181583
今日推荐