数据存储和访问方式五:网络
一、获取数据(图片、网页、xml、JSON等)
1.从网络获取一张图片,然后显示在手机上
①public byte [] getImageFromNet(){
try {
URL url = new URL("http://img10.360buyimg.com/n1/4987/9dceed99-e710-4ca8-b7f1-4e9dc01a0f75.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
byte [] data = readInputStream(inStream);//获取图片的二进制数据
//FileOutputStream outStream = new FileOutputStream("360buy.jpg");
//outStream.write(data);
//outStream.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
}
private byte [] readInputStream(InputStream inStream) throws IOException {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = inStream.read(buffer)) != -1){
byteOutputStream.write(buffer, 0, len);
}
inStream.close();
return byteOutputStream.toByteArray();
}
②使用ImageView组件显示图片。
③生成位图并设置到ImageView中
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
④在AndroidManifest.xml文件添加网络访问权限:
<uses-permission android:name="android.permission.INTERNET"/>
2.从网络获取指定网页的html代码,然后显示在手机上
①public String getHtmlCodeFromNet(){
try {
URL url = new URL("http://www.163.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
byte [] data = readInputStream(inStream);
String htmlString = new String(data, "gb2312");
System.out.println(htmlString);
return htmlString;
} catch (Exception e) {
e.printStackTrace();
}
}
②使用TextView组件显示网页代码
ScrollView 滚动条
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
/>
</ScrollView>
③在AndroidManifest.xml文件添加网络访问权限:
<uses-permission android:name="android.permission.INTERNET"/>
3.从服务器上获取最新的视频资讯信息,该信息以xml格式返回给Android客户端,然后列表显示在手机上。
>>最新资讯
喜羊羊与灰太狼 时长:60
盗梦空间 时长:120
生化危机 时长:100
①开发web端,在此采用Struts 2技术
②设计显示界面,使用ListView
③开发Android手机视频资讯客户端
注意:不能使用127.0.0.1或者localhost访问在本机开发的web应用
部分代码:
public List<Video> getXMLLastVideos(String urlPath) throws Exception{
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
return parseXML(inStream);
}
private List<Video> parseXML(InputStream inStream) throws Exception {
List<Video> videos = null;
Video video = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTf-8");
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
videos = new ArrayList<Video>();
break;
case XmlPullParser.START_TAG:
String name = parser.getName();
if("video".equals(name)){
video = new Video();
video.setId(new Integer(parser.getAttributeValue(0)));
}
if(video != null){
if("title".equals(name)){
video.setTitle(parser.nextText());
}else if("timeLength".equals(name)){
video.setTimeLength(new Integer(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:
String pname = parser.getName();
if("video".equals(pname)){
videos.add(video);
video = null;
}
break;
default:
break;
}
eventType = parser.next();
}
return videos;
}
④在AndroidManifest.xml文件添加网络访问权限:
<uses-permission android:name="android.permission.INTERNET"/>
4.从服务器上获取最新的视频资讯信息,该信息以JSON格式返回给Android客户端,然后列表显示在手机上。
服务器端需要返回的JSON数据:
[{id:1,title:"aaa1",timeLength:50},{id:2,title:"aaa2",timeLength:50},{id:3,title:"aaa3",timeLength:50}]
public List<Video> getJSONLastVideos(String urlPath) throws Exception{
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
byte [] data = StreamTools.readInputStream(inStream);
String json = new String(data);
JSONArray array = new JSONArray(json);
List<Video> videos = new ArrayList<Video>();
for(int i = 0;i < array.length(); i++){
JSONObject item = array.getJSONObject(i);
int id = item.getInt("id");
String title = item.getString("title");
int timeLength = item.getInt("timeLength");
videos.add(new Video(id, title, timeLength));
}
return videos;
}
二、通过HTTP协议提交文本数据(GET/POST)
GET、POST、HttpClient
1.通过GET方式提交参数给服务器:注意处理乱码(Android默认编码是UTF-8),提交的数据最大2K
①服务器端代码
HttpServletRequest request = ServletActionContext.getRequest();
//服务器端编码处理,先以ISO-8859-1编码得到二进制数据,然后使用UTF-8对数据重新编码
byte [] data = request.getParameter("title").getBytes("ISO-8859-1");
String titleString = new String(data, "UTF-8");
System.out.println("this.title==" + titleString);
System.out.println("this.timeLength==" + this.timeLength);
②客户端代码
public boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append('?');
if(params != null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey())
.append('=')
//对客户端发送GET请求的URL重新编码
.append(URLEncoder.encode(entry.getValue(), enc))
.append('&');
}
sb.deleteCharAt(sb.length()-1);
}
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
2.通过POST方式提交参数给服务器:
①<form method="post"/> 浏览器会把提交的数据转换成Http协议
②分析Http协议(使用HttpWatch)
第一部分:发送给服务器的
请求头部分(**********表示Http协议中必须提供的部分)
POST /videoweb/managerPost.action HTTP/1.1---(请求方式 请求路径 使用Http协议是1.1)
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, */* ---(浏览器接收的数据类型)
Referer: http://127.0.0.1:8081/videoweb/index.jsp---(请求来源,即从哪个页面发出请求的)
Accept-Language: zh-cn,en-US;q=0.5
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; CIBA; .NET CLR 2.0.50727) ---(用户的浏览器类型)
Content-Type: application/x-www-form-urlencoded ---(POST请求的内容类型)**********
Accept-Encoding: gzip, deflate
Host: 127.0.0.1:8081 ---(POST请求的服务器主机名和端口)**********
Content-Length: 46 ---(POST请求的内容长度,即实体数据部分的长度)**********
Connection: Keep-Alive ---(长连接)
Cache-Control: no-cache
Cookie: JSESSIONID=EFD762A0997BE1191DABFC311B345EE7
实体数据部分
title=aaa&timeLength=22&sub=%E6%8F%90%E4%BA%A4
第二部分:客户端接收到的
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Content-Length: 275