API.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.example.mytest;
  2. import org.json.JSONArray;
  3. import org.json.JSONObject;
  4. import java.io.DataInputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class API extends Thread {
  8. // адрес запроса
  9. public String url;
  10. // параметры, передаваемые с запросом
  11. public String param;
  12. public Interface context;
  13. @Override
  14. public void run() {
  15. try {
  16. URL _url = new URL(url);
  17. HttpURLConnection connection =
  18. (HttpURLConnection) _url.openConnection();
  19. connection.setRequestMethod("POST");
  20. connection.setRequestProperty("Content-Type", "application/json");
  21. connection.setDoOutput(true);
  22. connection.setDoInput(true);
  23. connection.getOutputStream().write(param.getBytes());
  24. connection.getOutputStream().flush();
  25. connection.connect();
  26. DataInputStream inputStream =
  27. new DataInputStream(connection.getInputStream());
  28. String response = inputStream.readLine();
  29. JSONObject json = new JSONObject(response);
  30. if (json.has("Error")) {
  31. if (!json.getString("Error").equals("null")) {
  32. System.out.println(json.getString("Error"));
  33. return;
  34. }
  35. if (json.has("News")) {
  36. if (!json.getString("News").equals("null")) {
  37. JSONArray news = json.getJSONArray("News");
  38. context.Main(news);
  39. }
  40. }
  41. }
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }