Android: AsyncTask para hacer una solicitud HTTP GET?

Soy nuevo en el desarrollo de Android. Mi pregunta es, ¿utilizo AsyncTask para hacer una petición HTTP GET (respuesta JSON)? ¿Es esto correcto? ¿Alguien sabe dónde puedo ver un ejemplo de esto si esto es verdad? Si no, ¿podría usted corregirme? ¡Gracias!

Si usted tiene razón, Asynctask se utiliza para la tarea de ejecución corta, como la conexión a la red. También se utiliza para la tarea de fondo para que usted no bloquear UI hilo o obtener excepción porque no puede hacer la conexión de red en su UI / hilo principal.

ejemplo:

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Boolean doInBackground(String... urls) { try { //------------------>> HttpGet httppost = new HttpGet("YOU URLS TO JSON"); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONObject jsono = new JSONObject(data); return true; } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return false; } protected void onPostExecute(Boolean result) { } 

Mira esto LINK y emaple de google esta buena también

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } 

Sí, tienes 3 opciones

  1. Uso de AsyncTask
  2. Puedes usar Handler
  3. O puede utilizar un seperate Thread .

La mejor opción es AsyncTask. Usted tiene que implementar su network call en el método doInBackground de AsyncTask y en método postExecute actualizar el main ui Thread o lo que quieras hacer ingenio con el resultado.

Puede seguir siga este tutorial para su requisito

fragmento de código

 @Override protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } 
 protected String doInBackground(String... strings) { String response = ""; response = ServiceHandler.findJSONFromUrl("url"); data = response; return response; } public class ServiceHandler { // Create Http connection And find Json public static String findJSONFromUrl(String url) { String result = ""; try { URL urls = new URL(url); HttpURLConnection conn = (HttpURLConnection) urls.openConnection(); conn.setReadTimeout(150000); //milliseconds conn.setConnectTimeout(15000); // milliseconds conn.setRequestMethod("GET"); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream(), "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } else { return "error"; } } catch (Exception e) { // System.out.println("exception in jsonparser class ........"); e.printStackTrace(); return "error"; } return result; } // method ends } 

Aquí es simple HttpsURLConnection en ASyncTask clase para Https POST / GET web-API llamando junto con paquete-header y JSONObject en cuerpo.

 import android.os.AsyncTask; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; /** * Class to handle BasicAuth post web-api call. */ public class Information extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { try { // Creating & connection Connection with url and required Header. URL url = new URL("https://example.com/wp-json/jwt-auth/v1/token"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("header-param_3", "value-3"); urlConnection.setRequestProperty("header-param_4", "value-4"); urlConnection.setRequestProperty("Authorization", "Basic Y2tfNDIyODg0NWI1YmZiZT1234ZjZWNlOTA3ZDYyZjI4MDMxY2MyNmZkZjpjc181YjdjYTY5ZGM0OTUwODE3NzYwMWJhMmQ2OGQ0YTY3Njk1ZGYwYzcw"); urlConnection.setRequestMethod("POST"); //POST or GET urlConnection.connect(); // Create JSONObject Request JSONObject jsonRequest = new JSONObject(); jsonRequest.put("username", "user.name"); jsonRequest.put("password", "pass@123"); // Write Request to output stream to server. OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); out.write(jsonRequest.toString()); out.close(); // Check the connection status. int statusCode = urlConnection.getResponseCode(); String statusMsg = urlConnection.getResponseMessage(); // Connection success. Proceed to fetch the response. if (statusCode == 200) { InputStream it = new BufferedInputStream(urlConnection.getInputStream()); InputStreamReader read = new InputStreamReader(it); BufferedReader buff = new BufferedReader(read); StringBuilder dta = new StringBuilder(); String chunks; while ((chunks = buff.readLine()) != null) { dta.append(chunks); } String returndata = dta.toString(); return returndata; } else { //Handle else case } } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } } 

Aquí el valor de Authentication (Header-parameter) es el valor codificado en Base64 de [API-key]:[API-Secret] agregando la cadena "Basic " en start.

En Android Studio, utilice la entrada Gradle como:

 compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5' 

AsyncTask gestiona su grupo de subprocesos, pero no está optimizado para la actividad de red. En realidad, si tiene muchas solicitudes HTTP en el mismo servidor, es mejor, tanto en términos de consumo de memoria como de rendimiento general, mantenerlas en el mismo hilo y reutilizar una conexión persistente, siempre que sea posible. AsyncTask no considera tales problemas.

En lugar de forjar su propio cliente HTTP asincrónico, considere utilizar una de las pocas bibliotecas disponibles. Algunas personas inteligentes invirtieron un montón de pensamiento en la toma de estos robusto, flexible y rápido.

  • Solicitud personalizada Angular2
  • Servidor ByetHost que pasa valores html "Comprobación de su navegador" con JSON String
  • VolleyPlus: NetworkDispatcher.run: Excepción no controlada java.lang.NullPointerException
  • Android: Volley HTTP Solicitar encabezado personalizado
  • ProtocolException: encabezado no válido:: en HTTPRequest
  • Subir fotos usando HttpPost MultiPartEntityBuilder
  • Proteger la solicitud HTTP de ser llamada por otros
  • Google TTS API para árabe, chino y griego
  • Uso de la biblioteca de actualización cuadrada para realizar solicitudes http
  • Compartir cookies desde la vista web con BasicHttpRequest en Android
  • Rutas dinámicas en la adaptación
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.