开发网络应用:URL、URLConnection、WebView详细使用方法;
- URL:
- 首先new一个URL(url)对象,需要传入一个网址
- 然后使用openStream打开输入流
- 然后就可以读取数据了。
- URLConnection 一般用于POST
- 首先创建一个URL对象
- 然后使用URL对象的openConnection方法返回一个URLConnection对象。
- 接着就可以设置一些文件头、参数了。conn.setConnectTimeout(5000);//设置链接超时为5秒 conn.addRequestProperty(“Accept”,”*/*”);//添加请求参数conn.addRequestProperty(“Connection”,”keep-alive”);
conn.addRequestProperty(“User-Agent”,”android os 0.002 “+ getPackageName());//可以改变请求头,下面会展示全部代码。
- WebView 这个主要是先演示一下 JS代码操作java对象类
- 主要的方法是web.addJavascriptInterface(new test(this),”mytest”);第一个参数是java对象,第二个参数是js调用的对象;js的代码如下:
mytest.showTip($("#text").val());mytest.showTip2();
- 主要的方法是web.addJavascriptInterface(new test(this),”mytest”);第一个参数是java对象,第二个参数是js调用的对象;js的代码如下:
解释完毕后现在贴出代码:
首先是URL的代码,代码中是读取网络上的一张图片,并且写出道内存卡中:
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(str);//创建一个URL对象(str是一张图片的网址)
InputStream in = url.openStream();//打开输入流
bitmap = BitmapFactory.decodeStream(in);//图片输出解码
mHandler.sendEmptyMessage(1);//发送消息,通知UI线程更新图片
String name = str.substring(str.lastIndexOf("/")+1);//截取图片的文件名
name = path+name;//组合路径:getPath(Environment.getExternalStorageDirectory()+"/lanxin/images")+name
Log.i(TAG,"name:"+name);
// OutputStream out = openFileOutput(name,MODE_WORLD_READABLE);
FileOutputStream out = new FileOutputStream(name); //申明一个文件输出流
byte[] b = new byte[1024*4]; //申请一个字节数组
int l = -1;//初始化长度变量
//循环读取图片字节数据
while ((l = in.read(b))!= -1){
out.write(b,0,l);//写出字节数据
}
in.close();//关闭输入流
out.close();//关闭输出流
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
代码是启动了一个线程去执行http数据读取的操作的,这样可以避免假死。
下面是URLConnection使用POST网络操作的代码:
new Thread(new Runnable() {
@Override
public void run() {
try {
//URLConnection对象发送网络请求的例子
URL url = new URL("http://192.168.1.205/1.php?ACT=1&D=SDF");//创建一个URL对象
URLConnection conn = url.openConnection(); //打开urlconn链接
conn.setConnectTimeout(5000);//设置链接超时为5秒
conn.addRequestProperty("Accept","*/*");//添加请求参数
conn.addRequestProperty("Connection","keep-alive");
conn.addRequestProperty("User-Agent","android os 0.002 "+ getPackageName());//可以改变请求头
//POST请求****start****
conn.setDoInput(true);//设置为POST请求
conn.setDoOutput(true);
PrintWriter pw = new PrintWriter(conn.getOutputStream());//创建PrintWriter对象
pw.print("user_name=123456&pwd=a001");//打印输出POST内容
pw.flush();//提交
//--end--
//conn.connect();//get的请求直接链接
Map<String,List<String>> map = conn.getHeaderFields();
for (String s : map.keySet()){
String val = String.valueOf(map.get(s));
Log.i(TAG,">>>> key:"+s+" val:"+val);
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());//取出输入流数据
BufferedReader br = new BufferedReader(in);//创建一个缓冲对象
String txt = ""; //初始化文本接收变量
String line = null; //初始化读取内容
//循环读取内容,不等于null就是读取成功
while ((line = br.readLine())!=null){
txt += line;
}
Log.i(TAG,txt);
br.close();//关闭缓冲对象
in.close();//关闭输入流
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
下面是webView绑定js对象的操作代码:
private void init() { web = (WebView) findViewById(R.id.webView); mContext = this; web.loadUrl("http://192.168.1.205/test/"); WebSettings webs = web.getSettings(); webs.setJavaScriptCanOpenWindowsAutomatically(true); webs.setJavaScriptEnabled(true); web.addJavascriptInterface(new test(this),"mytest");//绑定JS对象 } 以下是test类的代码:class test{ Context mContext; public test(Context ctx){ mContext = ctx; Log.i("TESTLOG","TEST"); } public void showTip(String str){ Toast.makeText(mContext,"test.showTip接口测试,输入的内容是:"+str,Toast.LENGTH_LONG).show(); } public void showTip2(){ for (int i =0 ;i < 20 ;i++){ Log.d("TESTLOG","TESTLOG:"+i); } Toast.makeText(mContext,"test.showTip2接口测",Toast.LENGTH_LONG).show(); } }
下面是webview读取test目录下index.html的代码片段:
<input type="text" id="text" value="">
<input type="button" id="showTip" value="showTip">
<input type="button" id="showTip2" value="showTip2">
<script>
$(document).ready(function(){
$("#showTip").click(function(){
mytest.showTip($("#text").val());
});
$("#showTip2").click(function(){
mytest.showTip2();
});
代码全部贴出来了,现在来上传一张效果图片:
URL 已经URLconnection操作的演示图片,but1 Onclick是URL读取网络上的一张图片,URLconnection操作的是读取一个网页数据,并且返回了一下数据信息,可以查看最后一行日志.
webview操作演示图片:



