2016-01-09 143 views

回答

10

尝试下面的代码从URL中获得JSON

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

在哪里可以找到HttpClient?我必须包含哪些软件包? – Tarion

+2

@Tarion只需在'android'中的应用级别build.gradle文件中添加'useLibrary'org.apache.http.legacy''在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

使用此函数从URL获取JSON。

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

不要忘了在你的清单

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

添加Internet权限,然后使用它是这样的:

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

很好的解决方案,不需要导入apache http客户端! – Jlange

+0

这里至少有两处重大错误。 1.'urlConnection.setDoOutput(true);'将请求更改为'POST'方法。 2.它有效地执行了两个请求,'new InputStreamReader(url.openStream())'再一次打开'url',不考虑'urlConnection'及其所有属性。''sb.append(line +“\ n”)'构建一个多余的字符串 –

4

我认为排球是最好的选择。

看到这个postpost

相关问题