欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

在android中请求JSON数据,android请求json,android获得jso

来源: javaer 分享于  点击 23633 次 点评:224

在android中请求JSON数据,android请求json,android获得jso


android获得json数据并处理:

//JsonActivity.javapackage cn.outofmemory.android;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.net.URI;import java.util.ArrayList;import java.util.List;import java.util.StringTokenizer;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.CoreProtocolPNames;import org.json.JSONArray;import org.json.JSONObject;import org.json.JSONStringer;import android.app.Activity;import android.os.Bundle;import android.os.Message;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;public class JsonActivity extends Activity {    Button button,buttonClear;    TextView textView;    String page;    String str="";     String url = "http://192.168.1.118/androidjsontest/index.php";    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        button = (Button) findViewById(R.id.btnFetch);        buttonClear = (Button) findViewById(R.id.btnClear);        textView = (TextView) findViewById(R.id.txtView);        button.setOnClickListener(new Button.OnClickListener()        {            public void onClick(View v)            {                examineJSONFile();            }        });        buttonClear.setOnClickListener(new Button.OnClickListener()        {            public void onClick(View v)            {                textView.setText("");            }        });    }    public String executeHttpGet(String URL) throws Exception     {        //This method  for HttpConnection          BufferedReader bufferedReader = null;        try         {            HttpClient client = new DefaultHttpClient();            client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");            HttpGet request = new HttpGet();            request.setHeader("Content-Type", "text/plain; charset=utf-8");            request.setURI(new URI(URL));            HttpResponse response = client.execute(request);            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));            StringBuffer stringBuffer = new StringBuffer("");            String line = "";            String NL = System.getProperty("line.separator");            while ((line = bufferedReader.readLine()) != null)             {                stringBuffer.append(line + NL);                System.out.print(stringBuffer);            }            bufferedReader.close();            page = stringBuffer.toString();            System.out.println(page+"page");            return page;        }         finally         {            if (bufferedReader != null)             {                try                 {                    bufferedReader.close();                }                 catch (IOException e)                    {                    Log.d("BBB", e.toString());                }            }        }    }    void examineJSONFile()    {        try        {            String Value="" ;            String str = "";            page = executeHttpGet(url);            Log.i("hello", str.toString());            JSONObject object=new JSONObject(page);            str=str+object.names().toString();            String sub1=str.substring(2, str.length()-2);            String[] names=sub1.split("\",\"");            for (int i=0;i<names.length;i++) {                Value=Value+names[i] +":"+object.get(names[i])+"\n";                System.out.println(names[i]);            }           /* String sub=str.substring(1, str.length()-1);            String[] names=sub.split(",");            String[] keyValue=new String[names.length];            for (int i=0;i<names.length;i++) {                names[i]=names[i].replace("\"","");                Value=Value+names[i] +":"+object.get(names[i])+"\n";                //keyValue[i]=names[i] +":"+object.get(names[i])+"\n";                System.out.println(names[i]);            }*/            textView.setText(Value);             /*for(int i=0;i<keyValue.length;i++){                textView.setText(keyValue[i]);            }*/            Log.i("hello", str.toString());        }        catch (Exception je)        {            textView.setText("Error w/file: " + je.getMessage());        }    }}

main.xml代码:

//==================<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:background="#acd654"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Button android:text="Fetch_Data"         android:id="@+id/btnFetch"         android:layout_width="match_parent"          android:layout_height="wrap_content"></Button> <Button android:text="Clear_Screen"         android:id="@+id/btnClear"         android:layout_width="wrap_content"          android:layout_height="wrap_content"></Button><TextView android:text=""           android:gravity="center"          android:textColor="#000a44"          android:id="@+id/txtView"           android:layout_width="fill_parent"           android:layout_height="fill_parent"/></LinearLayout>

android menifest.xml

?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="cn.outofmemory.android"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".JsonActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.INTERNET"/></manifest>
相关栏目:

用户点评