OkHttpUtils.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package 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. public class OkHttpUtils {
  10. private static final OkHttpClient client = HttpClient.buildHttpClient();
  11. private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  12. private OkHttpUtils() {
  13. }
  14. // 同步 GET 请求
  15. public static Response getSync(String url) throws IOException {
  16. Request request = new Request.Builder()
  17. .url(url)
  18. .build();
  19. Call call = client.newCall(request);
  20. return call.execute();
  21. }
  22. // 同步 POST 请求
  23. public static Response postSync(String url, String json) throws IOException {
  24. RequestBody body = RequestBody.create(JSON, json);
  25. Request request = new Request.Builder()
  26. .url(url)
  27. .post(body)
  28. .build();
  29. Call call = client.newCall(request);
  30. return call.execute();
  31. }
  32. }