2017-03-05 42 views
-3

我正在构建一个应用程序,它将从网址下载JSON数据并将其显示在Android应用程序中。一些相当新的东西。将JSON数据下载到Android应用程序

我在下载json数据时遇到问题,请大家帮忙?

公共类MainActivity扩展AppCompatActivity {

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    ListView EmployeesList = (ListView) findViewById(R.id.EmployeesList); 




    HttpURLConnection urlConnection; 
    InputStream in = null; 
    try { 
     // the url we wish to connect to 
     URL url = new URL("http://localhost:8000/"); 
     // open the connection to the specified URL 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     // get the response from the server in an input stream 
     in = new BufferedInputStream(urlConnection.getInputStream()); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    // covert the input stream to a string 
    String response = convertStreamToString(in); 
    // print the response to android monitor/log cat 
    System.out.println("Server response = " + response); 

} 


public String convertStreamToString(InputStream is) { 
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); 
    return s.hasNext() ? s.next() : ""; 
} 

}

+0

什么麻烦/错误?你使用什么代码?我们无法猜测。 – sudo

+0

你是什么意思下载,你的意思是消费一个Web服务? – Mehdi

+0

@Mehdi我已经创建了web服务,我想用android studio从url下载数据 – GRattab

回答

1

有几种方法可以做到你想要的东西。我的建议是使用volley(作为最好,现代和相当好的库之一)来执行JSON解析。

Here is short example which will provide to you an idea how to do this.

请注意,这只是你如何执行行动,以实现自己的目标的想法!

另外,您可以通过POJO的HTTP请求处理,其他库来执行这些操作....有很多不同的方法。谷歌它,并选择最适合你的。

+0

没有PJO,没有办法 – GRattab

相关问题