https://www.jianshu.com/p/1fb294ec7e3b
http://square.github.io/retrofit/
You can refer to these 2 articles:
The company's annual lucky draw:
Interface: Get the status of the server (used to judge whether the lottery can be started)
url: http://192.168.16.105:8080/getServerStatus
method: Get
success: {"id":1,"start":0,"code": 3}
error: {"code":-1,"error":"failure reason"}
id: you can ignore
start: when start=1, the lottery can be started, when it is 0, the lottery cannot be drawn
code: this represents which round of the lottery
Interface: upload score to server
url: http://192.168.16.105:8080/uploadData
method: post
body: {"name":"zhangsan","score":"12"}
success: {"code":0 }
error: {"code":-1,"error":"failure reason"}
name: name
score: score, 1-10
name: name
score: 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,仅供参考。