关闭

简单的网络技术及数据解析

标签: android网络数据解析网络技术
226人阅读 评论(0) 收藏 举报
分类:
网络技术:

1 WebView访问网络:

public class MainActivity extends Activity {

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

        webView = (WebView)findViewById(R.id.web_view);
        //让WebView支持javaScript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://192.168.1.105:8080/");


    }
}

加个权限:
<uses-permission android:name="android.permission.INTERNET"/>


2 开启线程发送网络请求

    两种方式:
    1 HttpClient
    private void sendRequesWithHttpClient() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                try {

                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(
                            "http://www.360.com");
                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    if (httpResponse.getStatusLine().getStatusCode() == 200) {


                        HttpEntity httpEntity = httpResponse.getEntity();

                        String response = EntityUtils.toString(httpEntity,"utf-8");

                        //把结果传递到message
                        Message message = new Message();
                        message.what = SHOW_RESPONSE;

                        message.obj = response.toString();
                        //发送message到handler
                        handler.sendMessage(message);

                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

        }).start();
    }

    2 HttpURLConnection

    private void sendRequestWithHttpURLConnection() {
        // 
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://www.360.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    // 高效读入流
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    // 发送数据
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

1 2 都要结合一个Handler 即

    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
            case SHOW_RESPONSE:
                String response = (String)msg.obj;
                //在这里进行Ui操作,把结果显示到TextView中
                text.setText(response);
                break;

            default:
                break;
            }
        }
    };

Url的链接不要用www.baidu.com 


网络传输数据的解析:XML  和    JSON 

XML:
第一种方式Pull解析


第二种SAX 首先要新建一个类继承DefaultHandler

public class ContentHandler extends DefaultHandler {

    private String nodeName ;
    private StringBuilder id;
    private StringBuilder name;
    private StringBuilder version;


    @Override
    public void startDocument() throws SAXException{
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    @Override
    public void startElement(String uri,String localName,String qName,
            Attributes attributes) throws SAXException{
        //记录当前的结点名
        nodeName = localName;
    }

    @Override
    public void characters(char[] ch,int start,int length) throws SAXException{
        //根据当前的结点名判断将内容添加到不同的StringBuilder对象中
        if("id".equals(nodeName)){
            id.append(ch,start,length);
        }else if("name".equals(nodeName)){
            name.append(ch,start,length);
        }else if("version".equals(nodeName)){
            version.append(ch,start,length);
        }
    }

    @Override
    public void endElement(String uri,String localName,String qName) throws SAXException{

        if("app".equals(localName)){
            Log.d("ContentHandler", "id is "+id.toString().trim());
            Log.d("ContentHandler", "name is "+name.toString().trim());
            Log.d("ContentHandler", "version is "+version.toString().trim());

            //最后把StringBuilder清空,否则会影响下一次的读取
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    @Override
    public void endDocument() throws SAXException{

    }
}

然后再到MianActivity调用



JSON格式:
    解析方式:
    1 JSONObject
    //json的JSONObject解析
    private void parseJSONWithJSONObject(String jsondata){

        try {
            JSONArray jsonArray = new JSONArray(jsondata);

            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String id  = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");

                Log.d("id", "id is "+id);
                Log.d("name", "name is "+name);
                Log.d("version", "version is "+version);

            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    2 GSON 


    //json的GSON的解析方式---google开源
    //GSON能够把数据自动映射成一个对象,省了代码量
    //所以在这里我先新建一个App类
    //前提是要有GSON.jar包
    private void parseJSONWithGSON(String jsondata){
        Gson gson = new Gson();
        List<App> applist = gson.fromJson(jsondata, new TypeToken<List<App>>(){}.getType());

        for(App app:applist){
            Log.d("MainActivity", "id is "+app.getId());
            Log.d("MainActivity", "name is "+app.getName());
            Log.d("MainActivity", "version is "+app.getVersion());
        }
    }

然后再到MainActivity调用

public class MainActivity extends Activity {

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

    }

    private void sendRequesWithHttpClient() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                try {

                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(
                            "http://localhost:8080/Hello/data.xml");
                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = httpResponse.getEntity();

                        String response = EntityUtils.toString(httpEntity);

                        parseXMLWithPull(response);

                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

        }).start();
    }


    //SAX解析XML方法,与Pull解析的区别就是层次清晰
    //要新建一个ContentHandler extends DefaultHander{
        //重写五个方法
    //}
    private void parseXMLWithSAX(String xmldata){
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();

            XMLReader xmlReader = factory.newSAXParser().getXMLReader();

            ContentHandler handler = new ContentHandler();

            xmlReader.setContentHandler(handler);

            //开始解析
            xmlReader.parse(new InputSource(new StringReader(xmldata)));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }


    private void parseXMLWithPull(String xmldata) {
        // TODO Auto-generated method stub
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

            XmlPullParser xmlPullParser = factory.newPullParser();

            xmlPullParser.setInput(new StringReader(xmldata));

            int eventType = xmlPullParser.getEventType();

            String id = "";
            String name = "";
            String version = "";

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();

                switch (eventType) {
                case XmlPullParser.START_TAG: {
                    if ("id".equals(nodeName)) {
                        id = xmlPullParser.nextText();

                    }
                    if ("name".equals(nodeName)) {
                        id = xmlPullParser.nextText();

                    }
                    if ("version".equals(nodeName)) {
                        id = xmlPullParser.nextText();

                    }
                    break;

                }
                case XmlPullParser.END_TAG: {
                    if ("app".equals(nodeName)) {
                        Log.d("MainActivity", "id is " + id);
                        Log.d("MainActivity", "name is " + name);
                        Log.d("MainActivity", "version is " + version);
                    }
                    break;
                }
                default:
                    break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}


注意:以上数据的解析全部要以本电脑创建本地服务器并在wenapp目录下新建.xml
和.json 文件,同时保证在公网的情况下(即android端和电脑端同一个网络)进行访问
否则则访问不到

同时也别忘了添加权限
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17862次
    • 积分:390
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论
  • 图片加载器

    xiaoxxxlong: 能把 demo 地址给出来么 直接跑着测试哇。。最近开发需要处理图片的东东 ,,谢谢楼主