«

Android Http访问网络 学习(慕课网学习)

时间:2024-3-2 17:43     作者:韩俊     分类: Android


一:通过Http 下载百度源码加载到 WebView显示

1:需要访问网络必须先要获取网络权限:

<span style="font-family: Arial, Helvetica, sans-serif;">   <uses-permission android:name="android.permission.INTERNET" ></span>
    </uses-permission>
2:在xml文件 定义Webview。

3:因为网络数据加载延迟问题,所以必须要用线程类来显示网页:

package testHttp;

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 org.apache.http.HttpConnection;

import android.R.string;
import android.os.Handler;
import android.webkit.WebView;

public class HttpThread extends Thread{

    private String url;
    private WebView webView;
    private Handler handler;
    HttpThread(String url,WebView webView,Handler handler){
        this.url=url;
        this.webView=webView;
        this.handler=handler;
    }

    @Override
    public void run() {
        try {
            URL httpUrl=new URL(url); 

            try {
                HttpURLConnection httpConnection=(HttpURLConnection) httpUrl.openConnection();//建立http连接
                httpConnection.setReadTimeout(5000);//设置超时时间
                httpConnection.setRequestMethod("GET");//设置请求为GET方法

                final StringBuffer bufferString=new StringBuffer();//用Stringbuffer来存储读到的代码
                BufferedReader reader=new BufferedReader(new InputStreamReader(
                        httpConnection.getInputStream()));

                String str;
                while((str=reader.readLine())!=null)
                {
                    bufferString.append(str);
                }

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                      webView.loadData(bufferString.toString(), 
                               "text/html;charset=utf-8", null);//将webView显示到网页上,还是要想 Web一样设置其编码

                    }
                });

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

4:在MainActivity中建立线程,并传参数到Thread:

package testHttp;

import com.example.androidtest.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;

public class TestHttpActivity extends Activity{

    private WebView webView;
    private String urlString="http://www.baidu.com";
    Handler handler=new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.http_main_activity);
        webView=(WebView) findViewById(R.id.httpWebView);
        new HttpThread(urlString, webView, handler).start();
    }

}

二:使用http协议在app中加载图片:

1:手写也是网络权限;

2:在xml文件 定义ImageView。

3:使用http获取网络图片,但是不同的是现在要通过二进制流来获取图片了。

先用二进制流获取到图片到本地之后,再用本地地址打开图片到ImageView:

package testHttp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpConnection;

import android.R.string;
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 ImageView imageView;
    private Handler handler;
    HttpThread(String url,ImageView imageView,Handler handler){
        this.url=url;
        this.imageView=imageView;
        this.handler=handler;
    }

    @Override
    public void run() {
        try {
            URL httpUrl=new URL(url);

            try {
                HttpURLConnection httpConnection=(HttpURLConnection) httpUrl.openConnection();
                httpConnection.setReadTimeout(5000);
                httpConnection.setRequestMethod("GET");
                httpConnection.setDoInput(true); //允许写

                InputStream inputStream=httpConnection.getInputStream();
                FileOutputStream fileOutputStream=null;
                File downFile=null;
                String fileNameString=String.valueOf(System.currentTimeMillis());

                if(Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)){
                    File parentFile=Environment.getExternalStorageDirectory();//获取本地路径
                    downFile=new File(parentFile, fileNameString);

                    fileOutputStream = new FileOutputStream(downFile);
                    }

                byte[] bt=new byte[2*1024];

                int len;

                if(fileOutputStream!=null){
                    while((len=inputStream.read(bt))!=-1)
                    {
                        fileOutputStream.write(bt, 0, len);
                    }
                }
                final Bitmap bitmap=BitmapFactory.decodeFile(downFile.getAbsolutePath());

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        imageView.setImageBitmap(bitmap);
                    }
                });

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}




标签: android

热门推荐