2015-04-09 16 views
21

Le org.apache.http classi e la classe AndroidHttpClient sono stati deprecati in Android 5.1. Queste classi non vengono più mantenute e dovresti eseguire la migrazione di qualsiasi codice app utilizzando queste API alle classi URLConnection il più presto possibile.classi HTTP deprecate Android Lollipop 5.1

https://developer.android.com/about/versions/android-5.1.html#http

È raccomandato per passare alle classi URLConnection. Non c'è abbastanza documentato esattamente come effettuare la chiamata dopo l'app.

Attualmente sto usando questo

public void postData() 
{ 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

    try 
    { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 
    } 
    catch (ClientProtocolException e) 
    { 
     // TODO Auto-generated catch block 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
    } 
} 

Come posso farlo utilizzando UrlConnections?

+2

Vuoi dire qualcosa di simile - http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post? Vi consiglio di passare a Retrofit, aQuery o qualsiasi altra lib di HTTP in realtà. – Stan

+0

Hai controllato i documenti ufficiali? http://developer.android.com/reference/java/net/HttpURLConnection.html – random

+0

@stan La classe NameValuePair è obsoleta che viene utilizzata nella risposta accettata per il collegamento condiviso – Fahim

risposta

31

pensiero di condividere il mio codice utilizzando HttpURLConnection

public String performPostCall(String requestURL, 
      HashMap<String, String> postDataParams) { 

     URL url; 
     String response = ""; 
     try { 
      url = new URL(requestURL); 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(15000); 
      conn.setConnectTimeout(15000); 
      conn.setRequestMethod("POST"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 


      OutputStream os = conn.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(getPostDataString(postDataParams)); 

      writer.flush(); 
      writer.close(); 
      os.close(); 
      int responseCode=conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 
       String line; 
       BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       while ((line=br.readLine()) != null) { 
        response+=line; 
       } 
      } 
      else { 
       response="";  

      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return response; 
    } 

..........

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{ 
     StringBuilder result = new StringBuilder(); 
     boolean first = true; 
     for(Map.Entry<String, String> entry : params.entrySet()){ 
      if (first) 
       first = false; 
      else 
       result.append("&"); 

      result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
      result.append("="); 
      result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
     } 

     return result.toString(); 
    } 
+1

Questo funziona bene, ma ora HttpException è deprecato troppo ... –

+0

Grazie per la soluzione! – Umair

+0

Google fa schifo. Non posso credere che qui non ci sia una libreria o un wrapper affidabile per le richieste HTTP nell'API Android. – Kamil

0

Utilizzare questa httpmime-4.1-beta1.jar provare questo codice: -

String url = "http://www.yoursite.com/script.php"; 
HttpClient client = new DefaultHttpClient(); 
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
HttpPost postMethod = new HttpPost(url); 
MultipartEntity entity = new MultipartEntity(); 
try 
{ 
    entity.addPart("id", new StringBody("123")); 
    entity.addPart("stringdata", new StringBody("AndDev is Cool!")); 
    postMethod.setEntity(entity); 
    HttpResponse response; 
    response = client.execute(postMethod); 
    String result = EntityUtils.toString(response.getEntity()); 
    JSONArray ja = new JSONArray(result); 
    // ITERATE THROUGH AND RETRIEVE CLUB FIELDS 
    int n = ja.length(); 
    for (int i = 0; i < n; i++) 
    { 
     // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAYJSONObject jo = ja.getJSONObject(i); 
     // RETRIEVE EACH JSON OBJECT'S FIELDS 
     String status = jo.getString("status"); 
     // Log.e("status",status); 
    } 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
+3

io non voglio usare altri lib apache ... volevano utilizzare URLConnection – Fahim

3

E a proposito di utilizzare Volley? Sembra un'ottima scelta rispetto a URLConnection. E ha molti vantaggi nell'accodamento delle richieste.

Problemi correlati