API.java 1.8 KB

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