2016-01-09 22 views

risposta

10

Prova sotto codice per ottenere JSON da un URL

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget= new HttpGet(URL); 

HttpResponse response = httpclient.execute(httpget); 

if(response.getStatusLine().getStatusCode()==200){ 
    String server_response = EntityUtils.toString(response.getEntity()); 
    Log.i("Server response", server_response); 
} else { 
    Log.i("Server response", "Failed to get server response"); 
} 
+3

Dove trovare HttpClient? Che pacchetto devo includere? – Tarion

+2

@Tarion aggiungi semplicemente" useLibrary "org.apache.http.legacy'' nel file build.gradle a livello di app in' android' blocco sopra 'defaultConfig'. –

0
try { 
      String line, newjson = ""; 
      URL urls = new URL(url); 
      try (BufferedReader reader = new BufferedReader(new InputStreamReader(urls.openStream(), "UTF-8"))) { 
       while ((line = reader.readLine()) != null) { 
        newjson += line; 
        // System.out.println(line); 
       } 
       // System.out.println(newjson); 
       String json = newjson.toString(); 
       JSONObject jObj = new JSONObject(json); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
24

Utilizzare questa funzione per ottenere JSON dall'URL.

public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException { 
    HttpURLConnection urlConnection = null; 
    URL url = new URL(urlString); 
    urlConnection = (HttpURLConnection) url.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setReadTimeout(10000 /* milliseconds */); 
    urlConnection.setConnectTimeout(15000 /* milliseconds */); 
    urlConnection.setDoOutput(true); 
    urlConnection.connect(); 

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); 
    StringBuilder sb = new StringBuilder(); 

    String line; 
    while ((line = br.readLine()) != null) { 
     sb.append(line + "\n"); 
    } 
    br.close(); 

    String jsonString = sb.toString(); 
    System.out.println("JSON: " + jsonString); 

    return new JSONObject(jsonString); 
} 

Non dimenticare di aggiungere il permesso a Internet nel vostro manifesto

<uses-permission android:name="android.permission.INTERNET" />

Quindi utilizzare in questo modo:

try{ 
     JSONObject jsonObject = getJSONObjectFromURL(urlString); 
     // 
     // Parse your json here 
     // 
} catch (IOException e) { 
     e.printStackTrace(); 
} catch (JSONException e) { 
     e.printStackTrace(); 
} 
+2

bella soluzione, non richiede l'importazione del client http di apache! – Jlange

+0

Almeno due errori importanti qui. 1. 'urlConnection.setDoOutput (true);' cambia richiesta al metodo 'POST'. 2. Esegue efficacemente due richieste, 'new InputStreamReader (url.openStream()' apre 'url' ancora una volta, ignorando' urlConnection' e tutte le sue proprietà 3. 'sb.append (line +" \ n ")' costruisce un eccesso 'String'. –

4

I Think volley è la scelta migliore per questo.

vedono questo post e questo post

Problemi correlati