2015-06-19 18 views
9

Ho bisogno di Sync o Async HTTP Post/Get per ottenere dati HTML da Web-Service. Ricerco tutta la rete ma non riesco a dare un buon risultato.Come rendere Sync o Async HTTP Post/Get

Ho cercato di usare questi esempi:

ma niente di loro lavorano per me.

HttpClient e HttpGet è traversa out, errore:

"org.apache.http.client.HttpClient is deprecated "

Codice:

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(); 
} 
+0

potrebbe essere se si pubblica ciò che è l'errore nel tentativo può portare a risultato. – Sree

+0

Non è possibile eseguire app perché HttpClient e HttpGet è traversa out, errore è: "org.apache.http.client.HttpClient è deprecato" CODICE: try { HttpClient client = new DefaultHttpClient(); String getURL = "http://www.google.com"; HttpGet get = new HttpGet (getURL); HttpResponse responseGet = client.execute (ottieni); HttpEntity resEntityGet = responseGet.getEntity(); se (resEntityGet! = Null) {// fare qualcosa con la risposta } } catch (Exception e) { e.printStackTrace(); } –

+0

è necessario trovare il motivo per cui non è possibile eseguire il compilatore – Sree

risposta

7

L'esempio che ho postato qui sotto si basa su un esempio che ho trovato sui Docs sviluppatori Android. Potete trovare quell'esempio HERE, guardate che per un esempio più completo.

Sarete in grado di fare eventuali richieste HTTP con il seguente

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); 
    } 
} 

Si può giocare con il codice in base alle proprie esigenze

+0

Il compilatore non riconosce: HttpURLConnection, URL, openConnection(), ecc. vedere l'immagine: http://postimg.org/image/sjaav97yx/ –

+1

Aggiungere le importazioni che ho aggiunto al codice – Neil

+0

Ho aggiunto la libreria ma sono ancora presenti alcuni errori, vedi schermo: http : //postimg.org/image/re791wksx/ –

3

È possibile utilizzare Volley che ti dà tutto il necessario. Se decidi di usare AsyncTask e programmarlo da solo, ti consiglio di non avere AsyncTask all'interno della tua attività, ma piuttosto di inserirlo in una classe wrapper e utilizzare una callback per questo. Ciò mantiene la tua attività pulita e rende il codice di rete riutilizzabile. Che è più o meno quello che hanno fatto a Volley.

+1

Volley è un'ottima alternativa, e in realtà un'opzione migliore! – Neil

0
**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*/); 

****---------------------------------------------------------------*** 

Per la richiesta di post è sufficiente modificare: connection.setRequestMethod ("GET"); a

connection.setRequestMethod ("POST");