网络技术
WebView
public class MainActivity extends Activity{
private WebView webView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView =(WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);//调用了setJavaScriptEnabled()方法来让WebView支持JavaScript脚本
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView webView,String url){
view.loadUrl(url); //根据传入的参数再去加载新的网页
return true; //表示当前webView可以处理打开新网页的请求,不用借助系统浏览器
}
});
webView.loadUrl("http://www.baidu.com");
}
}
注:
调用了WebView 的setWebViewClient()方法,并传入了WebViewClient 的匿名类作为参数,然后重写了shouldOverrideUrlLoading()方法。这就表明当需要从一个网页跳转到另一个网页时,我们希望目标网页仍然在当前WebView 中显示,而不是打开系统浏览器。
使用HTTP协议访问网络
HttpURLConnection
URL url =new URL("http://www.baidu.com");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
//设置HTTP请求所使用的方法,常用的方法主要有两个,GET和POST
connection.setRequestMethod("GET");
//自由定制一些设置
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in=connection.getInputStream();
//可以调用disconnect()方法将这个HTTP连接关闭掉,如下所示
connection.disconnect();
Post请求
connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
HttpClient
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); //如果返回的数据中有中文的话,那么会出现乱码 String respose =EntityUtils.toString(entity,"utf-8");
}
//有时要在请求的时候,传递一些数据给服务器 也就是添加请求头
//在请求消息头中指定语言,保证服务器会返回中文数据
httpGet.addHeader("Accept-Language","zh-CN");
HttpPost请求
HttpPost httpPost=new HttpPost("http://www.baidu.com");
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","admin"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
数据解析
XML解析
Pull解析
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.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
SAX解析
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 {
}
}
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler handler = new ContentHandler();
// 将ContentHandler的实例设置到XMLReader中
xmlReader.setContentHandler(handler);
// 开始执行解析
xmlReader.parse(new InputSource(new StringReader(xmlData)));
JSON
比起XML,JSON的主要优势在于它的体积更小,在网络上传输的时候可以更省流量。
JsonObject
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);
}
Gson
//一个对象
Gson gson = new Gson();
Person person = gson.fromJson(jsonData, Person.class);
//对象集合
List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType());
实例:
public interface HttpCallbackListener{\
void onFinish(String response);
void onError(Exception e);
}
public class HttpUtil{
public static void sendHttpRequest(final String address,final HttpCallbackListener listener){
new Thread(new Runnable(){
public void run(){
HttpURLConnection connection=null;
try{
URL url = new URL(address);
connection =(HttpConnection)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);
}
if (listener != null) {
// 回调onFinish()方法
listener.onFinish(response.toString());
}
}catch(Exception e){}finally{
if (listener != null) {
// 回调onError()方法
listener.onError(e);
}
}finally{
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
调用
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
// 在这里根据返回内容执行具体的逻辑
//依旧还在子线程里,不能直接更新UI
}
@Override
public void onError(Exception e) {
// 在这里对异常情况进行处理
}
});