直接show you the code
我使用的是聚合数据的api接口,朋友们您们可以自行找api进行试验,也可以申请聚合数据的api接口。
xml的布局很简单,就不贴代码了,主要两个按钮,第一个得到结果的按钮是得到返回的json数据,第二个按钮是进行json解析。
public class MainActivity extends AppCompatActivity { private TextView textView; private Button button; //url地址 private String url="http://japi.juhe.cn/joke/content/list.from?" + "key="+(你自己的key)+"&dtype=json&sort=asc&page=2&pagesize=4&time=1418816972"; private String line=""; //设置handler类,现在android已经不支持主线程直接使用网络通信,必须在线程里面使用 private Handler mhandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView= (TextView) findViewById(R.id.textView); button= (Button) findViewById(R.id.button); mhandler=new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what==1){ String s=msg.obj.toString(); textView.setText(s); } } }; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { //获得url URL uri=new URL(url); //建立连接 HttpURLConnection connection= (HttpURLConnection) uri.openConnection(); //设置连接方式 connection.setRequestMethod("GET"); //设置读数据的最大时间,超出时间则错误 connection.setReadTimeout(3000); //设置连接最大时间 connection.setConnectTimeout(3000); connection.connect(); //获取输入流 InputStream inputStream=connection.getInputStream(); //将字节流转换成字符流 BufferedReader bufferedReader=new BufferedReader( new InputStreamReader(inputStream,"UTF-8")); //获取string数据 StringBuilder stringBuilder=new StringBuilder(); if ((line=bufferedReader.readLine())!=null){ stringBuilder.append(line); } //发送消息给mhanlder Message message=new Message(); message.what=1; message.obj=stringBuilder.toString(); mhandler.sendMessage(message); //记得关闭 bufferedReader.close(); inputStream.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }); } }这样就能获取到数据了,记得在android的manifest加上internet连接权限,然后得到的数据如下所示
因为我设置textview的height等于wrap_content,所以变成了这样的布局,下面给出的json的解析过程。
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
StringBuilder sb=new StringBuilder();
JSONObject jsonObject=new JSONObject(s);
int code=jsonObject.getInt("error_code");
if (code!=0){
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT);
}
JSONObject object=jsonObject.getJSONObject("result");
JSONArray jsonArray=object.getJSONArray("data");
for (int i=0;i<jsonArray.length();i++){
JSONObject arrayobject=jsonArray.getJSONObject(i);
sb.append(arrayobject.getString("content"));
sb.append("\r\n");
}
textView2.setText(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
这是聚合数据提供的返回的json格式
我只对content的内容进行了解析,其他的解析过程是类似的,在此我就不多写了。
结果如下:
有什么不会的地方或者还需要补充的地方,欢迎道友指正~