您的位置:首页 > 理论基础 > 计算机网络

Http的使用及XML和JSON数据解析

2015-11-01 17:49 507 查看
一、Handler及Messsage机制

1、handler用于处理消息,譬如更新UI,执行耗时任务等,主线程中执行耗时任务则需要开启新线程。Message则用来在主线程中发送消息,发送的消息会在message queen中,由looper分发给handler处理。

二、HttpURLConnection用来访问网络及文件IO流操作

1、HttpURLConnection建立起网络连接,进行基本设置,再取得流对象进行网络操作。获取方式如下

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();
// InputStream in =url.openStream();

2、读取网络图片

URL url = new URL("http://192.168.1.100/yintao.jpg");// 手机访问本地服务器地址,使用本地IP地址
// 打开该URL对应的资源的输入流
InputStream is = url.openStream();
// 从InputStream中解析出图片
bitmap = BitmapFactory.decodeStream(is);
is.close();

3、读取网络文本

URL url = new URL(<a target=_blank href="http://192.168.1.100/doc.txt">http://192.168.1.100/doc.txt);</a>
InputStream is = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String string;
if ((string = reader.readLine()) != null) {
stringBuilder = stringBuilder.append(string);
}

4、存储网络数据到本地

URL url = new URL(<a target=_blank href="http://192.168.1.100/yintao.jpg">http://192.168.1.100/yintao.jpg</a>);
InputStream is = url.openStream();
// 打开手机文件对应的输出流
OutputStream os = openFileOutput("crazyit.png",MODE_WORLD_READABLE);
byte[] buff = new byte[1024];
int hasRead = 0;
// 将URL对应的资源下载到本地
while ((hasRead = is.re
4000
ad(buff)) > 0) {
os.write(buff, 0, hasRead);
}
is.close();
os.close();

三、使用HttpClient

1、获取数据并发送数据

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");<pre class="html" name="code">						Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);<pre class="html" name="code">}



四、解析数据

1、使用Pull解析XML

// 创建XML解析器工厂
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
// 得到XML PULL解析器
XmlPullParser xmlPullParser = factory.newPullParser();
// 传入XML数据
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;
}<pre class="html" name="code">				// 完成解析某个结点
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();
}

2、使用SAX解析XML

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)));<pre class="html" name="code">	//
class ContentHandler extends DefaultHandler {

private String nodeName;
private StringBuilder id;
private StringBuilder name;
private StringBuilder version;

public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
}

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;
}

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);
}
}

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);
}
}

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

}

3、使用JSONObject解析JSON

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");
}

4,定义工具类实现http请求

interface HttpCallbackListener {
void onFinish(String response);

void onError(Exception e);
}

public class HttpUtil {

/**
* @param args
*/
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) 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) {
if (listener != null) {
// 回调onError()方法
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络 数据 io流 xml json