1. 程式人生 > >Http訪問網路(AsyncTask 非同步載入和使用HttpURLConnection)

Http訪問網路(AsyncTask 非同步載入和使用HttpURLConnection)

兩種方式訪問百度,並且將伺服器所傳回的值設定在TextView中。用AsyncTask來實現

一、HttpURLConnection

步驟:

    URL url = new URL("http://www.baidu.com");

    HttpURLConnection connection = url.openConnection();

   //此處connection可設定請求方式和連線超時、讀取超時的秒數

    //connection.setRequestMethod("GET")

    InputStream in = connection.getInputStream();

    //可以根據輸入流來讀取資料

    connection.disconnnect();

如果想給伺服器提交資料:需要將requestedMethod改為POST,並且再獲取輸入流執之前將要提交的資料寫出即可

每條資料以鍵值對方式存在,資料與資料之間用&隔開

connection.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream("connection.getOutputStream()");

out.writeBytes("username=admin&passwd=123456");

二、HttpClient的方式:

HttpClient是一個介面,因此無法建立它的例項,一般通過DefaultHttpClient來建立例項

步驟:

HttpClient httpClient = new DefaultHttpClient();

//如果發起GET請求

HttpGet httpGet = new HttpGet("http://www.baidu.com");

HttpResponse response =httpClient.execute(httpGet);

執行execute 方法之後,會返回一個HttpResponse物件,伺服器返回的資訊就會包含在這裡面

取伺服器返回的狀態碼,如果等於200,則說明請求和響應都成功了

if(resonse.getStatusLine().getStatusCode()==200){

//首先獲得HttpEntity物件

HttpEntity entity = response.getEntity();

//EntityUtils.toString得到最終的結果

String result = EntityUtils.toString(entity,"utf-8");

}

但是,如果是POST請求,則比GET請求稍微麻煩一點 

httpPost-->NameValuePair-->BasicNameValuePair--->UrlEncodedFormEntity--->setEntity

 //如果發起POST請求

HttpPost   httpPost = new HttpPost("http://www.baidu.com");

//通過NameValuePair來存放待提交的資料

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("username","admin"));

params.add(new BasicNameValurPair("passwd","123"));

//將得到的引數集合傳到UrlEncodedFromEntity

UrlEncodedFormEntity entity= new UrlEncodedFormEntity(params,"utf-8");

httpPost.setEntity(entity);

之後的步驟就和GET一樣  httpClient.execute(httpPost);

BUT,當我在Android studio中基於API 22開發時,會發現用HttpClient ,編譯器會提示deprecated,也就是不贊成或者有更好的替代,所以不推薦用HttpClient

佈局:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/text"
            android:text="@string/hello_world" android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </ScrollView>

用HttpURLConnection程式碼:
     String url="http://www.baidu.com"
    TextView mTextView;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView)findViewById(R.id.text);
     
        new MyAsyncTask().execute(url);
    }
    //傳進去的是String型別的url地址,想得到伺服器返回的資料
    class MyAsyncTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            return getDataFromUrl(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mTextView.setText(s);
        }
    }
    //根據Url獲得輸入流,之後解析成String型別的資料
    public String getDataFromUrl(String url)  {
        HttpURLConnection connection;
        InputStream is = null;
        String result = "";
        String line ="";
        try {
            URL url1 = new URL(url);
            connection = (HttpURLConnection) url1.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line=bufferedReader.readLine())!=null){
                result +=line;
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return result;
    }