网络技术WebView,json,gson,HttpURLconnection

本文详细介绍了在Android中使用WebView加载网页的方法,包括支持JavaScript、处理页面跳转及使用HttpURLConnection和HttpClient发送HTTP请求等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>


 WebView webView;
 	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        webView=(WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient(){
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url) {
        		// TODO Auto-generated method stub
        		
        		view.loadUrl(url);
        		return true;
        	}
        });
        webView.loadUrl("http://www.baidu.com");
    }
    


MainActivity 中的代码也很短,首先使用 findViewById()方法获取到了 WebView 的实例,然后调用 WebView 的 getSettings()方法可以去设置一些浏览器的属性,这里我们
并不去设置过多的属性,只是调用了 setJavaScriptEnabled()方法来让 WebView 支持JavaScript 脚本。接下来是非常重要的一个部分,我们调用了 WebView 的 setWebViewClient()方法,并传入了 WebViewClient 的匿名类作为参数,然后重写了 shouldOverrideUrlLoading()方法。这就表明当需要从一个网页跳转到另一个网页时,我们希望目标网页仍然在当前WebView 中显示,而不是打开系统浏览器。最后一步就非常简单了,调用 WebView 的 loadUrl()方法,并将网址传入,即可展示相应网页的内容,这里就让我们看一看百度的首页是长什么样的吧


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.webviewtest"
 android:versionCode="1"
 android:versionName="1.0" >
 ⋯⋯
  <uses-permission android:name="android.permission.INTERNET" />
 ⋯⋯
</manifest>



使用 HTTP 协议访问网络

使用 HttpURLConnection


在 Android 上发送 HTTP 请求的方式一般有两种,HttpURLConnection 和HttpClient

HttpURLConnection:

首先需要获取到 HttpURLConnection 的实例,一般只需 new 出一个 URL 对象,并传入目标的网络地址,然后调用一下 openConnection()方法即可

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();


得到了 HttpURLConnection 的实例之后,我们可以设置一下 HTTP 请求所使用的方法。 常用的方法主要有两个, GET 和 POST。 GET 表示希望从服务器那里获取数据, 而 POST则表示希望提交数据给服务器

connection.setRequestMethod("GET");

接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
之后再调用 getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是对输入流进行读取
InputStream in = connection.getInputStream();
最后可以调用 disconnect()方法将这个 HTTP 连接关闭掉


connection.disconnect();

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Button" />

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="70dp"
            android:text="TextView" />
    </ScrollView>

</LinearLayout>


package com.example.webvieww;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{

	
	private static final int SHOW_RESPONSE=0;
	private Button sendRequest;
	private TextView responseText;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response=(String)msg.obj;
				responseText.setText(response);
			}
		};
	};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sendRequest=(Button) findViewById(R.id.button1);
        responseText=(TextView) findViewById(R.id.textView1);
        sendRequest.setOnClickListener(this);
    }


	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId()==R.id.button1) {
			sendRequestWithHttpURLConnection();
		}
	}


	private void sendRequestWithHttpURLConnection() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpURLConnection connection=null;
				try {
					URL url=new URL("http://www.baidu.com");
					connection=(HttpURLConnection)url.openConnection();
				    connection.setRequestMethod("GET");
				    connection.setConnectTimeout(8000);
				    connection.setReadTimeout(8000);
				    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) {
					// TODO: handle exception
					e.printStackTrace();
				}finally{
					if (connection!=null) {
						connection.disconnect();
					}
				}
			}
		}).start();
	}
    
}

<uses-permission android:name="android.permission.INTERNET" />




那么如果是想要提交数据给服务器应该怎么办呢?其实也不复杂,只需要将 HTTP 请求的方法改成 POST,并在获取输入流之前把要提交的数据写出即可。注意每条数据都要以
键值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密码

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");


	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId()==R.id.button1) {
			sendRequestWithHttpClient();
		}
	}


	private void sendRequestWithHttpClient() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
				// TODO Auto-generated method stub
				HttpClient httpClient=new DefaultHttpClient();
				HttpGet httpGet=new HttpGet("http://www.baidu.com");
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode()==200) {
					HttpEntity entity=httpResponse.getEntity();
					String response=EntityUtils.toString(entity,"utf-8");
					Message message=new Message();
					message.what=SHOW_RESPONSE;
					message.obj=response.toString();
					handler.sendMessage(message);
				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}


添加了一个 sendRequestWithHttpClient()方法,并在 Send Request 按钮的点击事件里去调用这个方法。在这个方法中同样还是先开启了一个子线程,然后在子线程里使用 HttpClient 发出一条 HTTP 请求,请求的目标地址还是百度的首页,HttpClient 的用法也正如前面所介绍的一样。然后为了能让结果在界面上显示出来,这里仍然是将服务器返回的数据存放到了 Message 对象中,并用 Handler 将Message 发送出去。



解析 XML 格式数据

网络上传输数据时最常用的格式有两种,XML 和 JSON

解析 XML 格式的数据其实也有挺多种方式

Pull解析和 SAX 解析

private void sendRequestWithHttpClient() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
				// TODO Auto-generated method stub
				HttpClient httpClient=new DefaultHttpClient();
				HttpGet httpGet=new HttpGet("http:/10.0.2.2/get_data.xml");
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode()==200) {
					HttpEntity entity=httpResponse.getEntity();
					String response=EntityUtils.toString(entity,"utf-8");
					Message message=new Message();
					message.what=SHOW_RESPONSE;
					message.obj=response.toString();
					handler.sendMessage(message);
				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
	}

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();
			}else if ("name".equals(nodename)) {
				name=xmlPullParser.nextText();
			}else if ("version".equals(nodename)) {
				version=xmlPullParser.nextText();
			}
			break;
		
		case XmlPullParser.END_TAG:
			if ("app".equals(nodename)) {
				Log.i("MainActivity","id is"+id);
				Log.i("MainActivity","name is"+name);
				Log.i("MainActivity","version is"+version);
			}
			break;
			default:
				break;
		}
		eventType=xmlPullParser.next();
		
	}
} catch (Exception e) {
	// TODO: handle exception
	e.printStackTrace();
}
}


可以看到,这里首先是将 HTTP 请求的地址改成了 http://10.0.2.2/get_data.xml,10.0.2.2 对于模拟器来说就是电脑本机的 IP 地址。在得到了服务器返回的数据后,我们并
不再去发送一条消息,而是调用了 parseXMLWithPull()方法来解析服务器返回的数据。下面就来仔细看下 parseXMLWithPull()方法中的代码吧。这里首先要获取到一个
XmlPullParserFactory 的实例,并借助这个实例得到 XmlPullParser 对象,然后调用XmlPullParser 的 setInput()方法将服务器返回的 XML 数据设置进去就可以开始解析了。
解析的过程也是非常简单,通过 getEventType()可以得到当前的解析事件,然后在一个while 循 环 中 不 断 地 进 行 解 析 , 如 果 当 前 的 解 析 事 件 不 等 XmlPullParser.END_DOCUMENT,说明解析工作还没完成,调用 next()方法后可以获取下一个解析事件。在 while 循环中,我们通过 getName()方法得到当前结点的名字,如果发现结点名等于 id、name 或 version,就调用 nextText()方法来获取结点内具体的内容,每当解析完一个 app 结点后就将获取到的内容打印出来


SAX 解析方式


public class MyHandler extends DefaultHandler {

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

}

这五个方法一看就很清楚吧?startDocument()方法会在开始 XML 解析的时候调用,startElement()方法会在开始解析某个结点的时候调用, characters()方法会在获取结点中
内容的时候调用, endElement()方法会在完成解析某个结点的时候调用, endDocument()方法会在完成整个 XML 解析的时候调用。其中,startElement()、characters()和
endElement()这三个方法是有参数的,从 XML 中解析出的数据就会以参数的形式传入到这些方法中。 需要注意的是, 在获取结点中的内容时, characters()方法可能会被调用多次,一些换行符也被当作内容解析出来,我们需要针对这种情况在代码中做好控制


package com.example.webvieww;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class MyHandler extends DefaultHandler {

	
	String nodeName;
	StringBuilder id;
	StringBuilder name;
	StringBuilder version;
	
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		id=new StringBuilder();
		name=new StringBuilder();
		version=new StringBuilder();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		nodeName=localName;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		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 {
		// TODO Auto-generated method stub
	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 {
		// TODO Auto-generated method stub
		super.endDocument();
	}

}


可以看到, 我们首先给 id、 name 和 version 结点分别定义了一个 StringBuilder 对象,并在 startDocument()方法里对它们进行了初始化。每当开始解析某个结点的时候,
startElement()方法就会得到调用,其中 localName 参数记录着当前结点的名字,这里我们把它记录下来。接着在解析结点中具体内容的时候就会调用 characters()方法,我们会根据当前的结点名进行判断,将解析出的内容添加到哪一个 StringBuilder 对象中。最后在endElement()方法中进行判断,如果 app 结点已经解析完成,就打印出 id、name 和version 的内容。需要注意的是,目前 id、name 和 version 中都可能是包括回车或换行符的, 因此在打印之前我们还需要调用一下 trim()方法, 并且打印完成后还要将 StringBuilder的内容清空掉,不然的话会影响下一次内容的读取。


	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId()==R.id.button1) {
			sendRequestWithHttpClient();
		}
	}


	private void sendRequestWithHttpClient() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
				// TODO Auto-generated method stub
				HttpClient httpClient=new DefaultHttpClient();
				HttpGet httpGet=new HttpGet("http:/10.0.2.2/get_data.xml");
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode()==200) {
					HttpEntity entity=httpResponse.getEntity();
					String response=EntityUtils.toString(entity,"utf-8");
//					Message message=new Message();
//					message.what=SHOW_RESPONSE;
//					message.obj=response.toString();
//					handler.sendMessage(message);
					parseXMLWithSAX(response);
				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
	}

protected void parseXMLWithSAX(String xmlData) {
		// TODO Auto-generated method stub
		try {
			SAXParserFactory factory=SAXParserFactory.newInstance();
			XMLReader xmlReader=factory.newSAXParser().getXMLReader();
			MyHandler handler=new MyHandler();
			xmlReader.setContentHandler(handler);
			xmlReader.parse(new InputSource(new StringReader(xmlData)));
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

在得到了服务器返回的数据后,我们这次去调用 parseXMLWithSAX()方法来解析XML 数据。parseXMLWithSAX()方法中先是创建了一个 SAXParserFactory 的对象,然后再获取到 XMLReader 对象,接着将我们编写的 ContentHandler 的实例设置到XMLReader 中,最后调用 parse()方法开始执行解析就好了。


解析 JSON 格式数据

现在你已经掌握了 XML 格式数据的解析方式,那么接下来我们要去学习一下如何解析JSON 格式的数据了。比起 XML,JSON 的主要优势在于它的体积更小,在网络上传输的
时候可以更省流量。但缺点在于,它的语义性较差,看起来不如 XML 直观。

使用 JSONObject

		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
				// TODO Auto-generated method stub
				HttpClient httpClient=new DefaultHttpClient();
				HttpGet httpGet=new HttpGet("http:/10.0.2.2/get_data.xml");
				HttpResponse httpResponse=httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode()==200) {
					HttpEntity entity=httpResponse.getEntity();
					String response=EntityUtils.toString(entity,"utf-8");
//					Message message=new Message();
//					message.what=SHOW_RESPONSE;
//					message.obj=response.toString();
//					handler.sendMessage(message);
				parseJSONWithJSONOBject(response);
				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
	}

protected void parseJSONWithJSONOBject(String jsonData) {
		// TODO Auto-generated method stub
		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("MainActivity", "id is " + id);
				Log.d("MainActivity", "name is " + name);
				Log.d("MainActivity", "version is " + version);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

可以看到,解析 JSON 的代码真的是非常简单,由于我们在服务器中定义的是一个 JSON 数组,因此这里首先是将服务器返回的数据传入到了一个 JSONArray 对象中。然后循环遍历这个JSONArray,从中取出的每一个元素都是一个 JSONObject 对象,每个 JSONObject 对象中又会包含 id、name 和 version 这些数据。接下来只需要调用 getString()方法将这些数据取出,并打印出来即可




使用 GSON

如何你认为使用 JSONObject 来解析 JSON 数据已经非常简单了,那你就太容易满足了。谷歌提供的 GSON 开源库可以让解析 JSON 数据的工作简单到让你不敢想象的地步,
那我们肯定是不能错过这个学习机会的。不过 GSON并没有被添加到 Android官方的 API中, 因此如果想要使用这个功能的话,则必须要在项目中添加一个 GSON 的 Jar 包。 首先我们需要将 GSON 的资源压缩包下载下来,下载地址是:http://code.google.com/p/google-gson/downloads/list。





其中 gson-2.2.4.jar 这个文件就是我们所需要的了,现在将它拷贝到 NetworkTest项目的 libs 目录下,GSON 库就会自动添加到 NetworkTest 项目中了




package com.example.webvieww;

public class App {
	private String id;
	private String name;
	private String version;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
}


				HttpResponse httpResponse=httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode()==200) {
					HttpEntity entity=httpResponse.getEntity();
					String response=EntityUtils.toString(entity,"utf-8");
//					Message message=new Message();
//					message.what=SHOW_RESPONSE;
//					message.obj=response.toString();
//					handler.sendMessage(message);
			parseJSONWithGSON(response);
				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
	}

protected void parseJSONWithGSON(String jsonData) {
		// TODO Auto-generated method stub
		 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:

package com.example.a23httpurl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{

	
	public static final int SHOW_RESPONSE = 0;
	
	Button send;
	TextView response;
	
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SHOW_RESPONSE:
				String res=(String)msg.obj;
				response.setText(res);
				break;

			default:
				break;
			}
		};
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        send=(Button) findViewById(R.id.button1);
        response=(TextView) findViewById(R.id.response);
        send.setOnClickListener(this);
    }

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId()==R.id.button1) {
			sendRequestWithHttpClient();
		}
	}

	private void sendRequestWithHttpURLConnection() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			HttpURLConnection connection = null;
			try {
				URL url=new URL("http://www.baidu.com");
				connection=(HttpURLConnection) url.openConnection();
				connection.setRequestMethod("GET");
				connection.setConnectTimeout(8000);
				connection.setReadTimeout(8000);
				
				InputStream in=connection.getInputStream();
				BufferedReader reader=new BufferedReader(new InputStreamReader(in));
				StringBuilder res=new StringBuilder();
				String line;
				while ((line=reader.readLine())!=null) {
				res.append(line);
					
				}
				Message message=new Message();
				message.what=SHOW_RESPONSE;
				message.obj=res.toString();
				handler.sendMessage(message);
			} catch (Exception e) {
				// TODO: handle exception
			}finally{
				if (connection!=null) {
					connection.disconnect();
				}
			}
			
			}
		}).start();
	}
    private void sendRequestWithHttpClient(){
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					HttpClient httpClient=new DefaultHttpClient();
					HttpGet httpGet=new HttpGet("http://www.baidu.com");
					HttpResponse httpResponse=httpClient.execute(httpGet);
					if (httpResponse.getStatusLine().getStatusCode()==200) {
						HttpEntity httpEntity=httpResponse.getEntity();
						String response=EntityUtils.toString(httpEntity,"utf-8");
//						parseXMLWithPull(response);
//						parseXMLWithSAX(response);
//						parseJSONWithJSONObject(response);
//						Message message=new Message();
//						message.what=SHOW_RESPONSE;
     					parseJSONWithGson(response);
//						message.obj=response.toString();
//						handler.sendMessage(message);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}).start();
    }

	protected void parseJSONWithGson(String response2) {
		// TODO Auto-generated method stub
		//Gson gson = new Gson();
		//List<App> appList = gson.fromJson(response2, 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());
		//}
	
	}

	protected void parseJSONWithJSONObject(String response2) {
		// TODO Auto-generated method stub
		try {
			JSONArray jsonArray=new JSONArray(response2);
			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("MainActivity", "id is " + id);
				Log.d("MainActivity", "name is " + name);
				Log.d("MainActivity", "version is " + version);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	protected void parseXMLWithSAX(String response2) {
		// TODO Auto-generated method stub
		try {
			SAXParserFactory factory=SAXParserFactory.newInstance();
		    XMLReader xml=factory.newSAXParser().getXMLReader();
		    ContentHandler contentHandler=new ContentHandler();
		    
		    xml.setContentHandler(contentHandler);
		    xml.parse(new InputSource(new StringReader(response2)));
		    
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	protected void parseXMLWithPull(String response2) {
		// TODO Auto-generated method stub
		try {
			XmlPullParserFactory xmlPullParserFactory=XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser=xmlPullParserFactory.newPullParser();
			xmlPullParser.setInput(new StringReader(response2));
			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();
					}else if ("name".equals(nodeName)) {
						name=xmlPullParser.nextText();
					}else if ("version".equals(nodeName)) {
						version=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);
					}
				default:
					break;
				}
				eventType=xmlPullParser.next();
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

activity_main:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      
        android:layout_marginLeft="35dp"
        android:layout_marginTop="24dp"
        android:text="Button" />
    
    
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
      >
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/response"/>
    </ScrollView>
    
</LinearLayout>

ContentHandler;

package com.example.a23httpurl;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class ContentHandler extends DefaultHandler {

	
	String nodeName;
	StringBuilder name;
	StringBuilder id;
	StringBuilder version;
	
	
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
		id=new StringBuilder();
		name=new StringBuilder();
		version=new StringBuilder();
	}
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
	nodeName=localName;
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		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 {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);
		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 {
		// TODO Auto-generated method stub
		super.endDocument();
	}
}

app:

package com.example.a23httpurl;

public class App {

	
	String id;
	String name;
	String version;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值