下载:
如何请求数据网络?
网络通信,发送请求有两种方式,GET和POST;
HttpURLConnection的GET方式获取网络数据,get方式将参数放在url后一起传递过去,而且会被看到,一般不太安全,但是get方式只获取数据,不会更新数据。
需要注意哪些点:异步获取数据,否则会闪退;
如何下载电影,音乐,游戏(本质)
请求结果如何处理:
怎样解析xml:xml相对于json比较耗空间,例如,对于下面一段代码来说
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
从Linearlayout开始解析,接着是跟着属性值拆分,再根据属性值再进行拆分,属性里面等号接下来引号,引号里面就是他的value
常用的数据格式json
方便的GSON等来源库
创建activity_network.xml实现在Text中输入网址点击Button获取数据在TextView中显示出网址:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入网址"//hint提示,光标移动上去变灰色
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取数据"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结果"/>
获取数据就相当于下载下来
在network.java文件中:
public class NetworkActivity extends Activity implements View.OnClickListener {
private EditText mEditText;
private TextView mTextView;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
findViews();
setListeners();//点击事件
}
private void setListeners() {
mButton.setOnClickListener(this);
}
private void findViews() {
mEditText = (EditText) findViewById(R.id.editText);
mTextView = (TextView) findViewById(R.id.textView);
mButton = (Button) findViewById(R.id.button);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String url = getEditTextUrl();
// 请求网络数据
// 1.申请网络权限
new RequestNetworkDataTask().execute(url);//拿到url
break;
}
}
//请求数据
private String getEditTextUrl() {
return mEditText != null ? mEditText.getText().toString() : "";
}
private String requestData(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);//请求网络超时设置,当网络出现问题半分钟之内没有响应返回超时;
connection.setRequestMethod("GET");//
// GET POST
connection.connect();//请求连接;
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
String result = null;
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
char[] buffer = new char[1024];
reader.read(buffer);
result = new String(buffer);
}
else {
}
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 异步任务处理
class RequestNetworkDataTask extends AsyncTask<String,Integer,String>{
// 在后台work之前
@Override
protected void onPreExecute() {
super.onPreExecute();
// 主线程
// UI Loading
}
@Override
protected String doInBackground(String[] params) {
//
String result = requestData(params[0]);
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//执行完之后在主线程中
mTextView.setText(result);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
在MainiFest中申请权限:
<uses-permission android:name="android.permission.INTERNET"/>
XML解析有三种方式
SAX:基于事件驱动的解析
一个web标签中有四个小标签
<?xml version="1.0" encoding="utf-8"?>
<web>
<item id="0" url="http://www.baidu.com">百度</item>
<item id="1" url="http://www.taobao.com">淘宝</item>
<item id="2" url="http://www.qq.com">腾讯</item>
<item id="3" url="http://www.geekband.com">极客班</item>
</web>
在MainActivity中写测试命令:
private void testSAXParse() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
SAXParseHandler saxParseHandler = new SAXParseHandler();
xmlReader.setContentHandler(saxParseHandler);
InputStream inputStream = getResources().openRawResource(R.raw.test);
InputSource inputSource = new InputSource(inputStream);
xmlReader.parse(inputSource);
saxParseHandler.getXMLList();
// 简单写法
XMLReader xmlReaderTest = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xmlReaderTest.setContentHandler(new SAXParseHandler());
// 处理xml文件的
xmlReaderTest.parse(new InputSource(getResources().openRawResource(R.raw.test)));
// xml文件
// pull xml 里面才能读到
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test);
try {
while (xmlResourceParser.getEventType() != XmlResourceParser.END_DOCUMENT){
if(xmlResourceParser.getEventType() == XmlResourceParser.START_TAG){
String tagName = xmlResourceParser.getName();
if(TextUtils.equals(tagName, "item")){
String id = xmlResourceParser.getAttributeValue(0);
}
}
}
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
// DOM
}
public class SAXParseHandler extends DefaultHandler {
public static final String ITEM = "item";
List<WebURL> mWebURLs;
WebURL mWebURL;
int type = 1;
boolean mIsItem;
@Override
public void startDocument() throws SAXException {
super.startDocument();
mWebURLs = new ArrayList<>();
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
mWebURL = new WebURL();
if(TextUtils.equals(localName, ITEM)){
for (int i = 0; i < attributes.getLength(); i++) {
if(TextUtils.equals(attributes.getLocalName(i), "id")){
mWebURL.setID(Integer.valueOf(attributes.getValue(i)));
}
}
mIsItem = true;
}
mIsItem = false;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(TextUtils.equals(localName, ITEM)){
mWebURLs.add(mWebURL);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String content = String.valueOf(ch,start,length);
if(mIsItem){
mWebURL.setContent(content);
mIsItem = false;
}
}
public List<WebURL> getXMLList() {
return mWebURLs;
}
}
续更