使用HttpUrlConnection访问网络
在过去,Android中发送Http请求的方式一般有两种:HttpUrlConnection和HttpClient.由于HttpClient的API数量太多导致扩展性很差,在Android6.0系统中HttpClient的功能被完全去除了。
@Override
public void onClick(View view) {
if (view.getId() == R.id.send_request) {
sendRequestWithHttpUrlConnection();
}
}
private void sendRequestWithHttpUrlConnection() {
//在Android3.0之后所有网络请求均需要在异步线程中执行
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//向百度发送请求
URL url = new URL("https://www.baidu.com");
//使用构造的url开启一个连接
connection = (HttpURLConnection) url.openConnection();
//设置网络请求方式为GET,主要需要大写
connection.setRequestMethod("GET");
//设置连接超时时间
connection.setConnectTimeout(8000);
//设置读取超时时间
connection.setReadTimeout(8000);
InputStream is = connection.getInputStream();
//对获取到的输入流数据进行读取
reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
//对读取到的数据进行拼接
response.append(line);
}
//对读取到的数据进行显示
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭对应的流操作
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//断开连接
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//只要在主线程中才能进行Ui操作
responseText.setText(result);
}
});
}
URL的书写一定不能出现错误
数据解析
解析XMl数据
使用Apache在本地搭建一个网页服务器,并在服务器上准备以下xml数据
lisa
girl
Bob
boy
Mike
boy
Pull解析
Student实体类
public class Student {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
'}';
}
/**
* 使用okHttp发送网络请求
*/
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//指定访问的服务器地址是电脑本机
.url("http://10.0.2.2/test.xml")
.build();
Response response = client.newCall(request).execute();
//取得返回的数据
String responseData = response.body().string();
Log.d("MainActivity", " " + responseData);
parseXmlWithPull(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseXmlWithPull(String xmlData) {
try {
//构造XmlPullParserFactory对象进一步得到XmlPullParse对象
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
//将服务器返回的xml数据设置进去开始解析
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
//未遍历到xml文件的结尾
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventType) {
//开始解析节点
case XmlPullParser.START_TAG: {
if ("name".equals(nodeName)) {
//使用xmlPullParser.nextText()方法取出对应的值
student.setName(xmlPullParser.nextText());
} else if ("gender".equals(nodeName)) {
student.setGender(xmlPullParser.nextText());
}
break;
}
//完成解析某个节点
case XmlPullParser.END_TAG: {
if ("student".equals(nodeName)) {
Log.d("MainActivity", " " + student.toString());
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Log日志如下
SAX解析
public class ContentHandler extends DefaultHandler {
private String nodeName;
private StringBuilder name;
private StringBuilder gender;
//开始XML解析时调用
@Override
public void startDocument() throws SAXException {
//变量初始化
name = new StringBuilder();
gender = 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 {
//根据节点名判断要将内容添加到哪个对象中
if ("name".equals(nodeName)) {
//拼接数据
name.append(ch, start, length);
} else if ("gender".equals(nodeName)) {
gender.append(ch, start, length);
}
}
//完成解析某个节点时调用
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("student".equals(localName)) {
Log.d("ContentHandler", "name is " + name.toString().trim());
Log.d("ContentHandler", "gender is " + gender.toString().trim());
//将StringBuilder清空,避免影响下一次数据的读取
name.setLength(0);
gender.setLength(0);
}
}
//完成整个XML解析时调用,一般调用父类的方法即可
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
private void parseXmlWithSAX(String responseData) {
try {
//获取SAXParseFactory对象
SAXParserFactory factory = SAXParserFactory.newInstance();
//使用SAXParseFactory对象进一步获取到XMLReader对象
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler handler = new ContentHandler();
//将ContentHandler实例设置到XMLReader中
xmlReader.setContentHandler(handler);
//开始解析
xmlReader.parse(new InputSource(new StringReader(responseData)));
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Log日志
DOM解析
//DOM解析XML数据
private void parseXmlWithDOM(String responseData) {
try {
//获取DOM解析器的工厂实例
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//从工厂实例中获取DOM解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//将要解析的xml数据读入解析器
Document document = builder.parse(new InputSource(new StringReader(responseData)));
//得到xml文件中名称为student的节点集合
NodeList studentNodes = document.getElementsByTagName("student");
//遍历该节点集合,获取集合中的元素及其子元素的值
for (int i = 0; i < studentNodes.getLength(); i++) {
Element student = (Element) studentNodes.item(i);
String name = student.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
String gender = student.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
Log.d("DOM", "name is " + name);
Log.d("DOM", "gender is " + gender);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Log日志
解析Json数据
在服务器准备Json数据源
[
{
"name": "Mike",
"gender": "boy",
"age": 19,
"family": [
{
"name": "Bob",
"gender": "boy",
"age": 21
},
{
"name": "Lily",
"gender": "girl",
"age": 18
}
]
},
{
"name": "lisa",
"gender": "girl",
"age": 20
}
]
JSONObject解析
//使用JsonObject解析Json数据
private void parseJsonWithJsonObject(String responseData) {
try {
//将服务器返回的数据传入JsonArray对象中
JSONArray jsonArray = new JSONArray(responseData);
for (int i = 0; i < jsonArray.length(); i++) {
//从JsonArray对象中取出最外层的JsonObject对象
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String gender = jsonObject.getString("gender");
int age = jsonObject.getInt("age");
Log.d("Json", "name is " + name);
Log.d("Json", "gender is " + gender);
Log.d("Json", "age is " + age);
//进一步从最外层的JsonObject获取次外层的JsonArray
JSONArray jsonArray_family = jsonObject.getJSONArray("family");
for (int j = 0; j < jsonArray_family.length(); j++) {
//获取次外层的JsonObject对象
JSONObject jsonObject_family = jsonArray_family.getJSONObject(j);
String family_name = jsonObject_family.getString("name");
String family_gender = jsonObject_family.getString("gender");
int family_age = jsonObject_family.getInt("age");
Log.d("Json", "family_name is " + family_name);
Log.d("Json", "family_gender is " + family_gender);
Log.d("Json", "family_age is " + family_age);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log日志