HttpURLConnection擷取資料

來源:互聯網
上載者:User

標籤:end   parse   main   utils   net   this   開啟   turn   pat   

使用步驟:

1.建立Url

2.用Url開啟串連

3.佈建要求參數

4. 擷取響應狀態代碼

  2xxx 請求成功 3xxx重新導向 4xxx資源錯誤 5xxx伺服器錯誤

5.擷取伺服器返回的二進位輸入資料流

6.添加網路許可權
  <uses-permission android:name="android.permission.INTERNET"/>

 

範例程式碼:

import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.Toast;public class MainActivity extends Activity {   private EditText   etPath;   private ImageView  iv;   private String     path;   @Override   protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_main);      etPath = (EditText) findViewById(R.id.et_path);      // 在主線程中建立      iv = (ImageView) findViewById(R.id.iv);   }   // 1. 在主線程中建立Hanlder對象   Handler  mHandler = new Handler() {      public void handleMessage(Message msg) {         // 把圖片顯示在imageview上         iv.setImageBitmap((Bitmap)msg.obj);      };   };   // 3. 在handleMessage()中修改UI   /**    * 1. 擷取伺服器返回的二進位輸入資料流     * 2. 把流轉成位元影像對象     * 3. 把圖片顯示在imageview上    */   public void look(View v) {      System.out.println("點擊按鈕的線程:" + Thread.currentThread().getName());       path = etPath.getText().toString().trim();      if (TextUtils.isEmpty(path) || !path.startsWith("http")) {         Toast.makeText(this, "請輸入正確的網址", 0).show();         return;      }      // 開啟線程      new Thread() {         public void run() {            requestNetWork();         };      }.start();   }   /**    * 網路通訊    */   protected void requestNetWork() {      try {         // 1. 寫一個Url         URL url = new URL(path);         // 2. 用這個Url開啟http串連         HttpURLConnection conn = (HttpURLConnection) url.openConnection();         // 3. 佈建要求參數         // 不設定,預設就是get請求         conn.setRequestMethod("GET");         conn.setConnectTimeout(3000);         // 4. 擷取狀態嗎         // * 2xxx響應成功 3xxx重新導向 4xxx資源錯誤 5xxx伺服器錯誤         int code = conn.getResponseCode();         if (code == 200) {            // 5. 擷取服務返回的二進位輸入資料流            InputStream is = conn.getInputStream();            // 把流轉成位元影像對象            Bitmap bmp = BitmapFactory.decodeStream(is);            // 2. 在子線程中用handler發訊息            Message msg = new Message();            msg.obj = bmp;            mHandler.sendMessage(msg);         } else {            // Toast.makeText(this, "code:"+code, 0).show();       }      } catch (Exception e) {         e.printStackTrace();         // Toast.makeText(this, "伺服器忙", 0).show();      }   }}
查看網路文字範例程式碼import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {   private static final int MSG_SUCC    = 0;   private static final int MSG_ERR         = 1;   private static final int MSG_ERR_CODE = 2;   private EditText         etPath;   private TextView         tvContent;   private String           path;   @Override   protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(R.layout.activity_main);      etPath = (EditText) findViewById(R.id.et_path);      tvContent = (TextView) findViewById(R.id.tv);   }   /**    *  1. 擷取使用者輸入的網址,做非空判斷    *  2. 在子線程中進行網路通訊     *  3. 擷取伺服器返回的位元據流    *  4. 把流轉成文字     *  5. 用Handler顯示文字    */   public void look(View v) {      // 擷取使用者輸入的網址,做非空判斷      path = etPath.getText().toString().trim();      if (TextUtils.isEmpty(path) || !path.startsWith("http")) {         Toast.makeText(this, "親,請輸入正確的網址,例如http開頭", 0).show();         return;      }      // 在子線程中進行網路通訊      new Thread() {         public void run() {            requestNetWork();         };      }.start();   }   /**    * 擷取伺服器返回的位元據流    */   protected void requestNetWork() {      try {         // 1. 寫一個Url         URL url = new URL(path);         // 2. 用這個Url開啟http串連         HttpURLConnection conn = (HttpURLConnection) url.openConnection();         // 3. 佈建要求參數         conn.setRequestMethod("GET");         conn.setConnectTimeout(3000);         // 4. 擷取狀態嗎         // * 2xxx響應成功 3xxx重新導向 4xxx資源錯誤 5xxx伺服器錯誤         int code = conn.getResponseCode();         if (code == 200) {            // 5. 擷取服務返回的二進位輸入資料流            InputStream is = conn.getInputStream();            // 把流轉成文字            String text = StringUtils.parseStream2Str(is);            // 用Handler顯示文字            Message msg = Message.obtain();// 從訊息池中擷取訊息            msg.obj = text;            msg.what = MSG_SUCC;            mHandler.sendMessage(msg);         } else {            Message msg = Message.obtain();// 從訊息池中擷取訊息            msg.obj =  code;            msg.what =MSG_ERR_CODE;            mHandler.sendMessage(msg);         }      } catch (Exception e) {         e.printStackTrace();         mHandler.sendEmptyMessage(MSG_ERR);      }   }   Handler  mHandler = new Handler() {      public void handleMessage(Message msg) {        switch (msg.what) {           case MSG_SUCC:              tvContent.setText((String) msg.obj);                break;            case MSG_ERR_CODE:               Toast.makeText(MainActivity.this, "code:"+msg.obj, 0).show();                break;            case MSG_ERR:                Toast.makeText(MainActivity.this, "伺服器忙", 0).show();                break;            default:                break;         }      };   };}
import java.io.ByteArrayOutputStream;import java.io.InputStream;/** * 操作字元 */public class StringUtils {   /**    * 從流中轉成字串    *     * @param is    *            輸入資料流    * @return null表示失敗    */   public static String parseStream2Str(InputStream is) {      //記憶體輸出資料流      ByteArrayOutputStream baos = new ByteArrayOutputStream();      int len = -1;      byte[] buffer = new byte[1024*8];      try {         while((len = is.read(buffer)) != -1){            baos.write(buffer, 0, len);         }         return new String(baos.toByteArray());      } catch (Exception e) {         e.printStackTrace();         return null;      }   }} 

 

HttpURLConnection擷取資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.