Android 获取 json


Android 获取 json

MainActivity.java
package com.example.jsontest;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

	 public TextView myTextView = null;

	   @Override

	   protected void onCreate(Bundle savedInstanceState) {

	      // TODO Auto-generated method stub

	      super.onCreate(savedInstanceState);

	      this.setContentView(R.layout.activity_main);
	      
	      this.myTextView=(TextView) findViewById(R.id.textView1);

	      Button btn = (Button)this.findViewById(R.id.button1);

	      btn.setOnClickListener(new Button.OnClickListener(){

	 

	         @Override

	         public void onClick(View v) {
	        	 
	        	 try{

	              new ReadHttpGet().execute("http://192.168.1.31/json.js");
	              
	        	 }catch(Exception e){
	        		 
	        		 // TODO Auto-generated catch block

	 	            e.printStackTrace();
	        		 
	        	 }

	         }

	        

	      });

	   }

	    class ReadHttpGet extends AsyncTask<Object, Object, Object>

	    {

	 

	      @Override

	      protected Object doInBackground(Object... params) {

	         // TODO Auto-generated method stub

	        

	         HttpGet httpRequest = new HttpGet(params[0].toString());

	         try

	         {

	            HttpClient httpClient = new DefaultHttpClient();

	            HttpResponse httpResponse = httpClient.execute(httpRequest);

	           

	            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

	            {

	                String strResult = EntityUtils.toString(httpResponse.getEntity());

	                return strResult;

	            }

	            else

	            {

	                return "请求出错";

	            }

	         }

	         catch(ClientProtocolException e)

	         {

	           

	         }

	         catch (IOException e) {

	            // TODO Auto-generated catch block

	            e.printStackTrace();

	         }

	        

	         return null;

	      }

	 

	      @SuppressLint("NewApi") 
	      @Override

	      protected void onCancelled(Object result) {

	         // TODO Auto-generated method stub

	         super.onCancelled(result);

	      }

	 

	      @Override

	      protected void onPostExecute(Object result) {

	         // TODO Auto-generated method stub

	         super.onPostExecute(result);

	        

	         try

	         {

	            //创建一个JSON对象

	            //JSONObject jsonObject = new JSONObject(result.toString()).getJSONObject("parent");

	            //获取某个对象的JSON数组

	            JSONArray jsonArray = new JSONArray(result.toString());

	            StringBuilder builder = new StringBuilder();

	           

	            for(int i = 0; i<jsonArray.length(); i++)

	            {

	                //新建一个JSON对象,该对象是某个数组里的其中一个对象

	                JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);

	               

	                builder.append(jsonObject2.getString("id")); //获取数据

	                builder.append(jsonObject2.getString("title"));

	                builder.append(jsonObject2.getString("name"));

	            }

	            myTextView.setText(builder.toString());

	         }

	         catch (JSONException e) {

	            // TODO Auto-generated catch block

	            e.printStackTrace();

	         }

	        

	      }

	 

	      @Override

	      protected void onPreExecute() {

	         // TODO Auto-generated method stub

	         //super.onPreExecute();

	         Toast.makeText(getApplicationContext(), "开始HTTP GET请求", Toast.LENGTH_LONG).show();

	      }

	 

	      @Override

	      protected void onProgressUpdate(Object... values) {

	         // TODO Auto-generated method stub

	         super.onProgressUpdate(values);

	      }

	      

	    }


}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jsontest.MainActivity"
    tools:ignore="MergeRootFrame" >

      <TextView
          android:id="@+id/textView1"
          android:layout_width="match_parent"
          android:layout_height="174dp"
          android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="get" />

</FrameLayout>

 

AndroidManifest.xml 加上网络权限: <uses-permission android:name="android.permission.INTERNET" />

优质内容筛选与推荐>>
1、Hello World!
2、Linux 内核链表 【转】
3、11种设计模式精简总结
4、bzoj4025 二分图
5、作业


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn