下載:
如何請求數(shù)據(jù)網(wǎng)絡淮菠?
網(wǎng)絡通信,發(fā)送請求有兩種方式荤堪,GET和POST合陵;
HttpURLConnection的GET方式獲取網(wǎng)絡數(shù)據(jù),get方式將參數(shù)放在url后一起傳遞過去澄阳,而且會被看到拥知,一般不太安全,但是get方式只獲取數(shù)據(jù)碎赢,不會更新數(shù)據(jù)低剔。
需要注意哪些點:異步獲取數(shù)據(jù),否則會閃退肮塞;
如何下載電影襟齿,音樂,游戲(本質)
請求結果如何處理:
怎樣解析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開始解析,接著是跟著屬性值拆分烁设,再根據(jù)屬性值再進行拆分替梨,屬性里面等號接下來引號钓试,引號里面就是他的value
常用的數(shù)據(jù)格式json
方便的GSON等來源庫
創(chuàng)建activity_network.xml實現(xiàn)在Text中輸入網(wǎng)址點擊Button獲取數(shù)據(jù)在TextView中顯示出網(wǎng)址:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入網(wǎng)址"http://hint提示装黑,光標移動上去變灰色
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="獲取數(shù)據(jù)"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="結果"/>
獲取數(shù)據(jù)就相當于下載下來
在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();
// 請求網(wǎng)絡數(shù)據(jù)
// 1.申請網(wǎng)絡權限
new RequestNetworkDataTask().execute(url);//拿到url
break;
}
}
//請求數(shù)據(jù)
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);//請求網(wǎng)絡超時設置,當網(wǎng)絡出現(xiàn)問題半分鐘之內沒有響應返回超時弓熏;
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);
//執(zhí)行完之后在主線程中
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;
}
}
續(xù)更