Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中使用HttpURLConnection

Android中使用HttpURLConnection

編輯:關於Android編程

HttpURLConnection繼承了URLConnection,因此也可以向指定網站發送GET請求、POST請求。它在URLConnetion的基礎上提供了如下便捷的方法。

int getResponseCode():獲取服務器的響應代碼。
String getResponseMessage():獲取服務器的訪問信息。
String getRequestMethod():獲取發送請求的方法。
void setRequestMethod(String method):設置發送請求的方法。
我們通過兩個例子來體會一下:
一、將網站的內容顯示在界面上:
1、創建一個WebView

2、MainActivity.java

public class MainActivity extends Activity {

    private WebView webview;
    //通過Handler在子線程更新主界面的UI
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView) findViewById(R.id.webView);
        new HttpThread(http://www.sina.com, webview, handler).start();
    }
}

3、創建一個子線程

public class HttpThread extends Thread {
    private String url;
    private WebView webview;
    private Handler handler;
    //通過構造函數傳三個參數
    public HttpThread(String url, WebView webView, Handler handler) {
        this.url = url;
        this.webview = webView;
        this.handler = handler;
    }
    }
    @Override
    public void run() {
        try {
            URL httpUri = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod(GET);   
            final StringBuffer sb = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String str;
            while((str = reader.readLine()) != null)
            {
                sb.append(str);
            }
            handler.post(new Runnable() {

                @Override
                public void run() {
                //將數據加載到webview中
                    webview.loadData(sb.toString(), text/html;charset=utf-8, null);
                }
            });
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

4、在AndroidManifest中添加權限:
android:name=”android.permission.INTERNET”

二、根據URL地址下載一張圖片
1、創建一個webview

2、MainActivity.java

public class MainActivity extends Activity {

    private Handler handler = new Handler();
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView1);
        new     HttpThread(http://img5.duitang.com/uploads/item/201410/23/20141023211631_VKmfz.jpeg, imageView, handler).start();
    }

3、創建一個子線程



public class HttpThread extends Thread {
    private String url;
    private Handler handler;
    private ImageView imageView;
    public HttpThread(String url, ImageView imageView, Handler handler) {
        this.url = url;
        this.imageView = imageView;
        this.handler = handler;
    }
    @Override
    public void run() {
        try {
            URL httpUri = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod(GET);
            //設置可以讀取到輸入流
            conn.setDoInput(true);
            InputStream in = conn.getInputStream();
            FileOutputStream out = null;
            String fileName = String.valueOf(System.currentTimeMillis());
            File downloadFile = null;
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {
                //獲得SDcard的目錄文件
                File parent = Environment.getExternalStorageDirectory();
                downloadFile = new File(parent, fileName);
                out = new FileOutputStream(downloadFile);
            }
            //緩沖區
            byte[] b = new byte[2 * 1024];
            int len;
            if(out != null)
            {
                while((len = in.read(b)) != -1)
                {
                    out.write(b, 0, len);
                }
            }
            final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
            handler.post(new Runnable() {

                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

4、在AndroidManifest中添加權限:
android:name=”android.permission.WRITE_EXTERNAL_STORAGE”

這樣下載的圖片就顯示在界面上了。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved