OkHttpUtils.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package xn.update.http;
  2. import java.io.IOException;
  3. import okhttp3.Call;
  4. import okhttp3.MediaType;
  5. import okhttp3.OkHttpClient;
  6. import okhttp3.Request;
  7. import okhttp3.RequestBody;
  8. import okhttp3.Response;
  9. import xn.update.http.bean.AllLogInterceptor;
  10. public enum OkHttpUtils {
  11. INSTANCE;
  12. private final OkHttpClient client = new OkHttpClient.Builder()
  13. .addInterceptor(new AllLogInterceptor())
  14. .build();
  15. private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  16. private OkHttpUtils() {
  17. }
  18. // 同步 GET 请求
  19. public Response getSync(String url) throws IOException {
  20. Request request = new Request.Builder()
  21. .url(url)
  22. .build();
  23. Call call = client.newCall(request);
  24. return call.execute();
  25. }
  26. // 同步 POST 请求
  27. public Response postSync(String url, String json) throws IOException {
  28. RequestBody body = RequestBody.create(JSON, json);
  29. Request request = new Request.Builder()
  30. .url(url)
  31. .post(body)
  32. .build();
  33. Call call = client.newCall(request);
  34. return call.execute();
  35. }
  36. }