Cómo hacer Sync o Async HTTP Post / Get
Necesito Sync o Async HTTP Post / Get para obtener datos HTML desde Web-Service. Busco este Internet entero pero no puedo dar el buen resultado.
He intentado usar estos ejemplos:
- HttpURLConnection realiza siempre una solicitud GET en lugar de una solicitud POST a pesar de setDoOutput (true) y setRequestMethod ("POST")
- Detectar el tiempo de espera de la conexión de cliente de android java desde PHP
- Lectura de archivos de texto desde el servidor en Android
- Obtener el código de respuesta de HttpURLConnection en android
- Las cookies no se almacenan en la API de Webview android 21 y superiores
- Series de Android obtener / post y multipost solicitudes
- Jcabi.com
- Ejecutar solicitud de publicación HTTP en android
Pero nada de ellos trabajando para mí.
HttpClient
y HttpGet
es cruz hacia fuera, el error es:
"Org.apache.http.client.HttpClient está obsoleto"
Código:
try { HttpClient client = new DefaultHttpClient(); String getURL = "google.com"; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response } } catch (Exception e) { e.printStackTrace(); }
- ¿Apoya Android varias solicitudes HTTP al mismo tiempo?
- Enviar datos binarios a través de POST en android
- Twitter JSON API en el desarrollo de Android
- ¿Puedo saber cómo funciona el soporte de modificación 304 No Modifield?
- Cómo hacer cookies persistentes con un DefaultHttpClient en Android?
- Límite de mensajería en la nube de Google
- Práctica recomendada para gestionar la llamada de error HTTP
- Android Async Http Obtener solicitud
El ejemplo que he publicado a continuación se basa en un ejemplo que encontré en los documentos para desarrolladores de Android . Usted puede encontrar ese ejemplo AQUÍ , mire eso para un ejemplo más comprensivo.
Podrá realizar cualquier solicitud de http con las siguientes
import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new DownloadTask().execute("http://www.google.com/"); } private class DownloadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { //do your request in here so that you don't interrupt the UI thread try { return downloadContent(params[0]); } catch (IOException e) { return "Unable to retrieve data. URL may be invalid."; } } @Override protected void onPostExecute(String result) { //Here you are done with the task Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); } } private String downloadContent(String myurl) throws IOException { InputStream is = null; int length = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = convertInputStreamToString(is, length); return contentAsString; } finally { if (is != null) { is.close(); } } } public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[length]; reader.read(buffer); return new String(buffer); } }
Usted puede jugar con el código para adaptarse a sus necesidades
Puedes usar Volley que te da todo lo que necesitas. Si decides usar AsyncTask y programarlo tú mismo, te recomiendo que no tengas AsyncTask dentro de tu Activity, sino que lo pongas en una clase wrapper y usas una devolución de llamada. Esto mantiene su actividad limpia y hace que el código de red sea reutilizable. Que es más o menos lo que hicieron en Volley.
**Async POST & GET request** public class FetchFromServerTask extends AsyncTask<String, Void, String> { private FetchFromServerUser user; private int id; public FetchFromServerTask(FetchFromServerUser user, int id) { this.user = user; this.id = id; } @Override protected void onPreExecute() { super.onPreExecute(); user.onPreFetch(); } @Override protected String doInBackground(String... params) { URL urlCould; HttpURLConnection connection; InputStream inputStream = null; try { String url = params[0]; urlCould = new URL(url); connection = (HttpURLConnection) urlCould.openConnection(); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.setRequestMethod("GET"); connection.connect(); inputStream = connection.getInputStream(); } catch (MalformedURLException MEx){ } catch (IOException IOEx){ Log.e("Utils", "HTTP failed to fetch data"); return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } protected void onPostExecute(String string) { //Do your own implementation } } ****---------------------------------------------------------------*** You can use GET request inn any class like this: new FetchFromServerTask(this, 0).execute(/*Your url*/); ****---------------------------------------------------------------***
Para la solicitud de correos simplemente cambie el: connection.setRequestMethod ("GET"); a
Connection.setRequestMethod ("POST");
- Longitud máxima de Android Sqlite String?
- ¿Soporta Android Wear HttpURLConnection – obtener EOFException