作者:韩亚飞_yue31313_韩梦飞沙 QQ:313134555
第一节、 访问网络的操作
一、知识概括
1、网络数据获取级综合案例
2、Get、post方式提交数据
3、客户端发送get、post请求及客户端上传数据
4、调用webService获取号码归属地
二、知识总结
1、网络数据获取级综合案例
访问网络都需要在清单文件中声明访问网络的权限
<uses-permissionandroid:name="android.permission.INTERNET"/>
在获取网页数据的时候需要一个输出流来获取服务器端的数据,包装一个简单的工具类,用来传递数据。
public staticbyte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = newByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len =is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
System.out.println(newString(result));
return result;
}
1)网络图片查看
public staticBitmap getImage(String address) throws Exception{
//通过代码模拟器浏览器访问图片的流程
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
//获取服务器返回回来的流
InputStream is =conn.getInputStream();
byte[] imagebytes =StreamTool.getBytes(is);
Bitmap bitmap =BitmapFactory.decodeByteArray(imagebytes, 0, imagebytes.length);
return bitmap; // bitmap就是一个图片的存储
}
2)网页代码源文件获取
public staticString getHtml(String address) throws Exception {
URL url = new URL(address);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");//可以不写,不写默认为get请求。
int code = conn.getResponseCode();//获取响应码
if (code == 200) {
InputStream is =conn.getInputStream();
byte[] result =StreamTool.getBytes(is);
String temp = newString(result);
// 简单描述原理
// 真实的代码需要解析meta里面的信息
if(temp.contains("gbk")) {
return new String(result,"gb2312");
} else {return temp;}
} else {
throw newIllegalStateException("访问网络失败");
}}
3)示例:微博界面
微博模式图
public ViewgetView(int position, View convertView, ViewGroup parent) {
View view =inflater.inflate(R.layout.item, null);
Channel channel =channels.get(position);
ImageView iv_item =(ImageView) view.findViewById(R.id.iv_item);
TextView tv_count =(TextView) view.findViewById(R.id.tv_count);
TextView tv_name =(TextView) view.findViewById(R.id.tv_name);
TextView tv_time =(TextView) view.findViewById(R.id.tv_time);
// 这句代码会产生问题么?
tv_count.setText("点播次数 " + channel.getCount());
tv_name.setText(channel.getName());
tv_time.setText("播放时间 " + channel.getTime());
String address =channel.getIcon();
int start =address.lastIndexOf("/");
String iconname = address.substring(start+ 1, address.length());
File file = newFile(Environment.getExternalStorageDirectory(),
iconname);
if (file.exists()&& file.length() > 0) {// 如果存在就直接使用 sd卡的文件
iv_item.setImageURI(Uri.fromFile(file));
System.out.println("使用缓存");
} else {
// 如果不存在 才去下载网络上的图片
try {
Bitmap bitmap= ImageUtil.getImage(address);
iv_item.setImageBitmap(bitmap);
System.out.println("下载新的图片");
} catch (Exceptione) {
e.printStackTrace();
iv_item.setImageResource(R.drawable.default_icon);
}
}
return view;
}
}
2、数据的两种提交方式
在提交数据的时候总是会出现乱码问题,对于这种问题可以通过encode方法的处理来避免乱码的出现。
String param1 =URLEncoder.encode(name);
Stringparam2 = URLEncoder.encode(password);
1)Get方式提交数据
public staticString sendDataByGet(String path, String name, String password)
throws Exception {
String param1 =URLEncoder.encode(name);
String param2 =URLEncoder.encode(password);
URL url = new URL(path +"?name=" + param1 + "&password=" + param2);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
// 数据并没有发送给服务器
// 获取服务器返回的流信息
InputStream is =conn.getInputStream();
byte[] result =StreamTool.getBytes(is);
return new String(result);
}
2)Post方式提交数据
public staticString sendDataByPost(String path, String name,
String password) throwsException {
String param1 =URLEncoder.encode(name);
String param2 =URLEncoder.encode(password);
URL url = new URL(path);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
String data = "name=" +param1 + "&password=" + param2;
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
// 设置 http协议可以向服务器写数据
conn.setDoOutput(true);
// 设置http协议的消息头
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",data.length() + "");
// 把我们准备好的data数据写给服务器
OutputStream os =conn.getOutputStream();
os.write(data.getBytes());
// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
int code = conn.getResponseCode();
if (code == 200) {
InputStream is =conn.getInputStream();
byte[] result =StreamTool.getBytes(is);
return new String(result);
} else {
throw newIllegalStateException("服务器状态异常");
}
}
3、Httpclien 的操作
1)发送get请求
public static StringsendDataByHttpClientGet (String path , String name,String password) throwsException{
//1.获取到一个浏览器的实例
HttpClientclient = new DefaultHttpClient();
//2.准备请求的地址
Stringparam1 = URLEncoder.encode(name);
Stringparam2 = URLEncoder.encode(password);
HttpGethttpGet = new HttpGet(path + "?name=" + param1 + "&password="+ param2);
//3.敲回车 发请求
HttpResponse ressponse = client.execute(httpGet);
intcode = ressponse.getStatusLine().getStatusCode();
if(code== 200){
InputStreamis =ressponse.getEntity().getContent();
byte[]result = StreamTool.getBytes(is);
returnnew String(result);
}
else{
thrownew IllegalStateException("服务器状态异常");
}
}
2)发送post请求
public staticString sendDataByHttpClientPost(String path , String name,String password)throws Exception{
//1. 获取到一个浏览器的实例
HttpClient client = newDefaultHttpClient();
//2. 准备要请求的 数据类型
HttpPost httppost = newHttpPost(path);
// 键值对
List< NameValuePair>parameters = new ArrayList<NameValuePair>();
parameters.add(newBasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("password",password));
UrlEncodedFormEntity entity = newUrlEncodedFormEntity(parameters, "utf-8");
//3.设置post请求的数据实体
httppost.setEntity(entity);
//4. 发送数据给服务器
HttpResponse ressponse = client.execute(httppost);
int code =ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte[] result =StreamTool.getBytes(is);
return new String(result);
}
else{
throw newIllegalStateException("服务器状态异常");}
}
3)Httpclient上传数据
public static String sendDataByHttpClientPost(Stringpath , String name,String password ,String filepath) throws Exception{
// 实例化上传数据的数组 part []
Part[] parts = {newStringPart("name", name),
new StringPart("password", password),
new FilePart("file", newFile(filepath))};
PostMethod filePost = newPostMethod(path);
filePost.setRequestEntity(newMultipartRequestEntity(parts, filePost.getParams()));
org.apache.commons.httpclient.HttpClientclient = new org.apache.commons.httpclient.HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status =client.executeMethod(filePost);
if(status==200){
System.out.println(filePost.getResponseCharSet());
String result = newString(filePost.getResponseBodyAsString());
String ha = new String (result.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(ha);
System.out.println("--"+result);
return result;
}
else{
throw new IllegalStateException("服务器状态异常");
}}}
4、练习:Websevvic查询号码归属地
public voidtestGetAddress() throws Exception{
URL url = newURL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
InputStream is =getClass().getClassLoader().getResourceAsStream("data.xml");
byte [] data =StreamTool.getBytes(is);
String str = new String(data);
String content =str.replace("$mobile", "13512345678");
System.out.println(content);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length",content.length()+"");
conn.getOutputStream().write(content.getBytes());
InputStream response =conn.getInputStream();
System.out.println( new String(StreamTool.getBytes(response)));
}
}