Advertisement
VladislavSavvateev

Untitled

Jan 8th, 2019
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.21 KB | None | 0 0
  1. import android.os.AsyncTask;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Random;
  12. import java.util.Scanner;
  13. import javax.net.ssl.HttpsURLConnection;
  14.  
  15. import org.json.JSONArray;
  16. import org.json.JSONObject;
  17.  
  18. public abstract class RequestSender extends AsyncTask<Void, Void, Object> {
  19.     public static final String URL = "https://wingstaxi.ru/api/";
  20.     public static final String ENCODING = "UTF-8";
  21.    
  22.     private JSONObject request;
  23.    
  24.     protected URL getURL() throws MalformedURLException {
  25.         return new URL(URL);
  26.     }
  27.  
  28.     protected int getReadTimeout() { return READ_TIMEOUT; }
  29.    
  30.     /**
  31.      * Формирует запрос с подписью, который будет отправлен на сервер
  32.      */
  33.     protected JSONObject onFormRequest() throws Throwable {
  34.         return null;
  35.     }
  36.  
  37.     /**
  38.      * Вызывается когда ответ успешно получен с сервера
  39.      */
  40.     protected abstract void onResponseReceived(JSONObject request, JSONObject response) throws Throwable;
  41.    
  42.     /**
  43.      * Вызывается при ошибке в формировании/отправке/обработке запроса
  44.      */
  45.     protected void onRequestFailed(JSONObject request, Throwable cause) {
  46.         cause.printStackTrace();
  47.     }
  48.  
  49.     @Override
  50.     protected final Object doInBackground(Void[] args) {
  51.         try {
  52.             request = onFormRequest();
  53.             return send(request);
  54.         } catch(Throwable e) {
  55.             try { Thread.sleep(1000); }
  56.             catch (InterruptedException ex) { ex.printStackTrace(); }
  57.             return e;
  58.         }
  59.     }
  60.  
  61.     @Override
  62.     protected final void onPostExecute(Object result) {
  63.         if(result instanceof JSONObject) {
  64.             try {
  65.                 onResponseReceived(request, (JSONObject)result);
  66.             } catch(Throwable e) {
  67.                 onRequestFailed(request, e);
  68.             }
  69.         } else {
  70.             onRequestFailed(request, (Throwable)result);
  71.         }
  72.     }
  73.    
  74.     protected JSONObject send(JSONObject request) throws Throwable {
  75.         HttpsURLConnection conn = null;
  76.         try {
  77.             conn = (HttpsURLConnection) getURL().openConnection();
  78.             conn.setReadTimeout(getReadTimeout());
  79.             conn.setConnectTimeout(CONNECT_TIMEOUT);
  80.             conn.setRequestMethod(request == null ? "GET" : "POST");
  81.             conn.setDoInput(true);
  82.             conn.setDoOutput(request != null);
  83.             conn.connect();
  84.  
  85.             if(Thread.interrupted()) throw new InterruptedException();
  86.  
  87.             if(request != null) {
  88.                 conn.getOutputStream().write(request.toString().getBytes(ENCODING));
  89.                 conn.getOutputStream().close();
  90.             }
  91.  
  92.             int responseCode = conn.getResponseCode();
  93.             if(responseCode == HttpsURLConnection.HTTP_OK) {
  94.                 StringBuilder sb = new StringBuilder();
  95.                 Scanner sc = new Scanner(conn.getInputStream(), ENCODING);
  96.                 while (sc.hasNextLine()) {
  97.                     sb.append(sc.nextLine());
  98.                     sb.append('\n');
  99.                 }
  100.  
  101.                 if(Thread.interrupted()) throw new InterruptedException();
  102.  
  103.                 conn.disconnect();
  104.  
  105.                 return new JSONObject(sb.toString());
  106.             } else {
  107.                 throw new IOException("Bad response: " + responseCode);
  108.             }
  109.         } catch(Throwable e) {
  110.             if(conn != null) conn.disconnect();
  111.             throw e;
  112.         }
  113.     }
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement