2016-01-09 25 views

Trả lời

10

Hãy thử mã dưới đây để có được json từ một 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

Nơi để tìm HttpClient? Gói nào tôi phải đưa vào? – Tarion

+2

@Tarion chỉ thêm' useLibrary 'org.apache.http.legacy'' vào tệp build.gradle ở cấp ứng dụng của bạn trong 'android' chặn trên '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

Sử dụng chức năng này để nhận JSON từ 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); 
} 

Đừng quên để thêm phép Internet ở của bạn manifest

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

Sau đó sử dụng nó như thế này:

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

đẹp giải pháp thấy, không yêu cầu nhập ứng dụng khách apache http! – Jlange

+0

Có ít nhất hai lỗi chính ở đây. 1. 'urlConnection.setDoOutput (true);' thay đổi yêu cầu thành phương thức 'POST'. 2. Nó thực thi hai yêu cầu một cách hiệu quả, 'InputStreamReader mới (url.openStream()' mở 'url' một lần nữa, bỏ qua' urlConnection' và tất cả các thuộc tính của nó. xây dựng một thừa 'Chuỗi'. –

4

Tôi nghĩ rằng cú volley là lựa chọn tốt nhất cho điều đó.

post này và điều này post

Các vấn đề liên quan