The problem is this: I write applications with a connection to the server. I make a simple AsyncTask with Callback. Everything is good, but with the problem with the connection, it is not processed as it should be but just throws it out. Here is the request code:
package com.example.drawer.drawer; import android.content.Context; import android.os.AsyncTask; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by user on 29.11.2017. */ public class AsyncQuery extends AsyncTask<String, String, String> { private Context context; private String postParams; private Callback callBack; private String constUrl; AsyncQuery(Context c, String url, String p, Callback back){ context = c; postParams = p; callBack = back; constUrl = url; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { try { String myURL = constUrl; String param = postParams; byte[] data = null; InputStream is = null; try { URL url = new URL(myURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length)); OutputStream os = conn.getOutputStream(); data = param.getBytes("UTF-8"); os.write(data); data = null; conn.connect(); int responseCode= conn.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (responseCode == 200) { is = conn.getInputStream(); byte[] buffer = new byte[8192]; // Такого вот размера буфер int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } data = baos.toByteArray(); String rs = new String(data, "UTF-8"); return rs; }else{ callBack.onReqFail(false); return null; } } catch (MalformedURLException e) { callBack.onFail("MalformedURLException:"); return null; } catch (IOException e) { callBack.onFail("IOException:"); return null; } catch (Exception e) { callBack.onFail("Exception:"); return null; } } catch (Exception e) { e.printStackTrace(); callBack.onFail("Exception:"); return null; } } @Override protected void onPostExecute( String rs) { super.onPostExecute(rs); if (rs != null){ callBack.onSuccess(rs); } } } And here is the callback code processing:
@Override public void onReqFail(Boolean str){ if (str == false){ TextView txt = (TextView) findViewById(R.id.statusForQuery); txt.setText("Ошибка сети проверте подключения к интернету"); } } @Override public void onFail(String rs) { TextView txt = (TextView) findViewById(R.id.statusForQuery); txt.setText(rs); } What do you think?