1-4 HttpUrlConnection介绍
例子1:访问百度网址
1.在AndroidManifest.xml添加权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2.在xml里添加webview组件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" /> </RelativeLayout>
3.在MainActivity.java里创建webview,以及对web初始化。
public class MainActivity extends Activity { // 1.创建webview private WebView web; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 2.对web初始化 web = (WebView) findViewById(R.id.webView1); } }
4.对网络进行初始化,新建一个类HttpThread,因为网络是耗时操作,所以得在线程中做一些处理。(
1)重写run方法,处理耗时操作。(2)创建一个参数,来传递URL
HttpThread.java
package com.example.http_01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.Handler; import android.webkit.WebView; public class HttpThread extends Thread{ private String url; private WebView webView; private Handler handler; public HttpThread(String url,WebView webView,Handler handler){ this.handler=handler; this.url=url; this.webView=webView; } public void run(){ try { URL httpUrl =new URL(url); // 对http的访问,用openConnection打开connection的对象 try { HttpURLConnection connection=(HttpURLConnection) httpUrl.openConnection(); // 网络访问的操作 // 1.请求超时的时间 connection.setReadTimeout(5000); // 2.网络请求的方式 connection.setRequestMethod("GET"); // 3.创建完成,为了拿到回访信息,创建一个stringbuffer做缓冲 final StringBuffer sBuffer=new StringBuffer(); // 创建包装类,字符流转字节流 BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream())); String string; // 读一行不等于空的时候继续读 while ((string=reader.readLine())!=null) { sBuffer.append(string); } handler.post(new Runnable() { @Override public void run() { webView.loadData(sBuffer.toString(),"text/html;charset=utf-8" , null); } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
MainActivity .java
package com.example.http_01; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.webkit.WebView; public class MainActivity extends Activity { // 1.创建webview private WebView web; private Handler handler=new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 2.对web初始化 web = (WebView) findViewById(R.id.webView1); new HttpThread("http://www.baidu.com", web, handler).start(); } }
步骤:
1.创建URL对象,URL就是我们统一资源的定位符的对象
2.通过URL,拿到一个Connectioin对象
3.通过connection设置一些请求的方式(用“GET”来请求网络的数据)
4.通过connection可以拿到读入流(网址的内容),拿到后放进BufferedReader缓冲区里面
5.通过每次读一行的情况下,把数据拿到StringBuffer当中
6.用WebView加载本地的html页面的信息
例二:通过网络请求下载图片,到本地展现出来的例子。
1.把WebView设置为隐藏,新增添一个ImageView
<WebView android:visibility="gone" android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
2.在MainActivity.java将ImageView初始化
public class MainActivity extends Activity { // 1.创建webview private WebView web; private ImageView imageView; private Handler handler=new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 2.对web初始化 web = (WebView) findViewById(R.id.webView1); imageView=(ImageView) findViewById(R.id.imageView1); new HttpThread("http://www.baidu.com", web, handler).start(); } }
3.在HttpThread添加构造方法,创造全局变量
private ImageView imageView; public HttpThread(String url, ImageView imageView, Handler handler) { this.handler = handler; this.url = url; this.imageView = imageView; }
4.拿到流的信息
connection.setDoInput(true); InputStream in =connection.getInputStream();
5.从网络读取图片,将图片下载到本地
判断ID卡是否存在 把图片写到ID卡
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java
package com.example.http_01; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.webkit.WebView; import android.widget.ImageView; public class MainActivity extends Activity { // 1.创建webview private WebView web; private ImageView imageView; private Handler handler=new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 2.对web初始化 web = (WebView) findViewById(R.id.webView1); imageView=(ImageView) findViewById(R.id.imageView1); new HttpThread("http://h.hiphotos.baidu.com/image/pic/item/6c224f4a20a446239e8d311c9b22720e0cf3d70d.jpg", imageView, handler).start(); } }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <WebView android:visibility="gone" android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
下载到SD卡:
HttpThread .java
package com.example.http_01; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.webkit.WebView; import android.widget.ImageView; public class HttpThread extends Thread { private String url; private WebView webView; private Handler handler; private ImageView imageView; public HttpThread(String url, WebView webView, Handler handler) { this.handler = handler; this.url = url; this.webView = webView; } public HttpThread(String url, ImageView imageView, Handler handler) { this.handler = handler; this.url = url; this.imageView = imageView; } public void run() { try { URL httpUrl = new URL(url); // 对http的访问,用openConnection打开connection的对象 try { HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); // 网络访问的操作 // 1.请求超时的时间 connection.setReadTimeout(5000); connection.setDoInput(true); // 2.网络请求的方式 connection.setRequestMethod("GET"); // A获取流的信息 InputStream in = connection.getInputStream(); FileOutputStream out = null; File downloadFile = null; // F系统时间 String fileName = String.valueOf(System.currentTimeMillis()); // C判断SD卡是否存在 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // DID卡的目录 File parent = Environment.getExternalStorageDirectory(); // E指定文件的名字 downloadFile = new File(parent, fileName); // B将图片下载到本地,在该目录写一个文件 out = new FileOutputStream(downloadFile); } // H写之前创建缓冲区,并指定长度 byte[] bs = new byte[2 * 1024]; int len; // G如果SD卡存在的话,往里面写 if (out != null) { // I通过间距读流判断 while ((len = in.read(bs)) != -1) { out.write(bs, 0, len); } } // K通过Bitmap传递路径的名字 final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath()); // J通过Handler更新UI handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // L往主页发送消息 imageView.setImageBitmap(bitmap); } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
下载到手机里:
package com.example.http_01; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.os.Handler; import android.webkit.WebView; import android.widget.ImageView; public class HttpThread extends Thread { private String url; private WebView webView; private Handler handler; private ImageView imageView; public HttpThread(String url, WebView webView, Handler handler) { this.handler = handler; this.url = url; this.webView = webView; } public HttpThread(String url, ImageView imageView, Handler handler) { this.handler = handler; this.url = url; this.imageView = imageView; } public void run() { try { URL httpUrl = new URL(url); // 对http的访问,用openConnection打开connection的对象 try { HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); // 网络访问的操作 // 1.请求超时的时间 connection.setReadTimeout(5000); connection.setDoInput(true);// 可以得到输入流 // 2.网络请求的方式 connection.setRequestMethod("GET"); // A获取流的信息 InputStream in = connection.getInputStream();// 图片的二进制流 final Bitmap bitmap=BitmapFactory.decodeStream(in); // J通过Handler更新UI handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // L往主页发送消息 imageView.setImageBitmap(bitmap); } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }