|
| 1 | +package track.club.couriermobile; |
| 2 | + |
| 3 | +import android.support.v4.util.Consumer; |
| 4 | +import android.util.Log; |
| 5 | +import com.google.gson.FieldNamingPolicy; |
| 6 | +import com.google.gson.Gson; |
| 7 | +import com.google.gson.GsonBuilder; |
| 8 | +import okhttp3.*; |
| 9 | + |
| 10 | +public class CourierAPI { |
| 11 | + private final OkHttpClient client; |
| 12 | + private final Gson gson = new GsonBuilder() |
| 13 | + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) |
| 14 | + .create(); |
| 15 | + private final RESTAcceptor<Courier> restAcceptor; |
| 16 | + private static final MediaType JSON |
| 17 | + = MediaType.parse("application/json; charset=utf-8"); |
| 18 | + |
| 19 | + |
| 20 | + public CourierAPI(OkHttpClient client) { |
| 21 | + this.client = client; |
| 22 | + this.restAcceptor = new RESTAcceptor<>(gson); |
| 23 | + } |
| 24 | + |
| 25 | + public void Create(Courier courier, final Consumer<Courier> consumer) { |
| 26 | + RequestBody body = RequestBody.create(JSON, gson.toJson(courier)); |
| 27 | + Request request = new Request.Builder() |
| 28 | + .post(body) |
| 29 | + .url("https://track-delivery.club/api/v1/couriers") |
| 30 | + .build(); |
| 31 | + client.newCall(request).enqueue(restAcceptor.onResponse(consumer, Courier.class)); |
| 32 | + } |
| 33 | + |
| 34 | + public void Update(Courier courier, final Consumer<Courier> consumer) { |
| 35 | + Gson gson = new Gson(); |
| 36 | + String json = gson.toJson(courier); |
| 37 | + RequestBody body = RequestBody.create(JSON, json); |
| 38 | + Request request = new Request.Builder() |
| 39 | + .put(body) |
| 40 | + .url("https://track-delivery.club/api/v1/couriers/" + courier.getId()) |
| 41 | + .build(); |
| 42 | + Log.i("update req", json); |
| 43 | + client.newCall(request).enqueue(restAcceptor.onResponse(consumer, Courier.class)); |
| 44 | + } |
| 45 | + |
| 46 | + public void Delete(Courier courier) { |
| 47 | + HttpUrl respURL = new HttpUrl.Builder() |
| 48 | + .scheme("https") |
| 49 | + .host("track-delivery.club") |
| 50 | + .addPathSegment("api/v1/couriers/") |
| 51 | + .addPathSegment(courier.getId()) |
| 52 | + .build(); |
| 53 | + |
| 54 | + Request request = new Request.Builder() |
| 55 | + .delete() |
| 56 | + .url(respURL) |
| 57 | + .build(); |
| 58 | + client.newCall(request).enqueue(restAcceptor.onEmptyResponse()); |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +} |
0 commit comments