Métodos obsoletos, cómo puedo reemplazarlo por nuevos

Tengo un problema con algunos métodos obsoletos, en particular con esto que he publicado aquí.

Lo que quiero es simple: enviar datos al servidor mediante http post —> hacer una consulta con los datos que recibo de un cliente -> enviar una respuesta

Estoy tratando de desarrollar una aplicación de Android utilizando API 6.0, pero todos mis métodos están obsoletos, lo que debo cambiar para convertir mi código con nuevo?

public class ReadServer extends Activity { String result; public String readserver(String id_data, String data){ try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("myurl/queryMobile.php"); StringBuilder builder = new StringBuilder(); String json = ""; //Build jsonObject JSONObject jsonObject = new JSONObject(); jsonObject.accumulate(id_data, data); //Convert JSONObject to JSON to String json = jsonObject.toString(); //Set json to StringEntity StringEntity se = new StringEntity(json); //Set httpPost Entity httpPost.setEntity(se); //Set some headers to inform server about the type of the content httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); //Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); //Receive response as inputStream StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); //Convert input stream to string AlertDialog.Builder alertDialog; switch(statusCode){ case 200: HttpEntity entity = httpResponse.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line=""; try{ while ((line = reader.readLine()) != null) { builder.append(line); result = builder.toString(); } }catch(Exception e){ alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("400 Bad Request"); alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi."); alertDialog.show(); } break; case 500: alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("500 Internal Server Error"); alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi."); alertDialog.show(); break; case 503: alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("503 Service Unavailable"); alertDialog.setMessage("Il server di ....non è al momento disponibile, riprova più tardi."); alertDialog.show(); break; case 504: alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("504 Gateway Timeout"); alertDialog.setMessage("Il server di ....è momentaneamente sovraccarico, riprova più tardi."); alertDialog.show(); break; default: alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Si è verificato un errore"); alertDialog.setMessage("Errore 001" +"\n"+"Non è stato possibile soddisfare la tua richiesta, riprova più tardi."); alertDialog.show(); break; } }catch(Exception e){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Si è verificato un errore"); alertDialog.setMessage("Errore 001" + "\n" + "Non è stato possibile soddisfare la tua richesta, riprova più tardi."); alertDialog.show(); } return result; } } 

Intenté cambiar algún método pero no sé cómo convertir algún procedimiento, por ejemplo:

SetEntity, HttpResponse, StatusLine …

Necesito absolutamente cambiar el método obsoleto con nuevo, no puedo cambiar todo el código.

EDIT 1: Por ejemplo, en mi MainActivity:

  ReadServer read = new ReadServer(); String result = read.readserver("list_news","homepage"); 

Mi clase ReadServer ingresa dos parámetros de entrada:

 public String readserver(String id_data, String data){ ... jsonObject.accumulate(id_data, data); // in a jsonObject i put two params ... } 

Hago un Http Post, mis datos se envían a mi servidor (mi página php)

 $raw = file_get_contents('php://input'); $value = json_decode($raw, true); $list_news = $value['list_news']; 

En este punto obtengo mis datos y puedo hacer mi consulta:

 if (isset($list_news)) { switch($list_news){ case "homepage": $q = "SELECT FROM WHERE "; 

Creo que puede referirse a mi siguiente código de ejemplo, a continuación, utilizar su lógica para su aplicación:

 private class POSTRequest extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { String address = "http://192.16.1.100:24780/api/token"; HttpURLConnection urlConnection; String requestBody; Uri.Builder builder = new Uri.Builder(); Map<String, String> stringMap = new HashMap<>(); stringMap.put("grant_type", "password"); stringMap.put("username", "bnk"); stringMap.put("password", "bnkpwd"); Iterator entries = stringMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString()); entries.remove(); } requestBody = builder.build().getEncodedQuery(); try { URL url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); // urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); JSONObject jsonObject = new JSONObject(); InputStream inputStream; // get stream if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } // parse stream BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String temp, response = ""; while ((temp = bufferedReader.readLine()) != null) { response += temp; } // put into JSONObject jsonObject.put("Content", response); jsonObject.put("Message", urlConnection.getResponseMessage()); jsonObject.put("Length", urlConnection.getContentLength()); jsonObject.put("Type", urlConnection.getContentType()); return jsonObject.toString(); } catch (IOException | JSONException e) { return e.toString(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.i(LOG_TAG, "POST\n" + result); } } 

ACTUALIZAR:

Con su código PHP, puede probar la siguiente actualización:

 ... JSONObject json = new JSONObject(); json.put("key1", "sample value..."); requestBody = json.toString(); URL url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); ... 

Puede leer más en las clases HTTP obsoletas .

Otras buenas soluciones para su referencia:

  • Okhttp
  • Voleo
  • Reequipamiento

¡Espero que esto ayude!

  • Diferencia entre ConnectionTimeoutException y SSLException con el mensaje "Tiempo de espera de conexión agotado"
  • Accountmanager vs sharedpreference para la autenticación y la comunicación con el servidor
  • Android: solicitud de revisión de Volley HTTP
  • Cómo detener el ataque hack / DOS en la API web
  • No se puede realizar el almacenamiento en caché HTTP en android
  • Android DefaultHTTPConnection con Keep-Alive no reutiliza la conexión TCP
  • La validación de URL funciona bien, pero mantiene la conexión y restringe las solicitudes adicionales
  • Cómo abrir un servidor HTTP en reaccionar nativo
  • Acceso localhost desde el teléfono móvil
  • Cómo interceptar datos POST en una vista web de android
  • ¿Cómo crear un servidor nanohttpd en android?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.