天天看點

HTTP

package com.yanjun;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity {

  /** Called when the activity is first created. */

  Button button = null;

  // 伺服器端接收請求後傳回的響應----httpResponse

  HttpResponse httpResponse;

  // httpEntity代表接收的http消息

  HttpEntity httpEntity = null;

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

      public void onClick(View v) {

        // 首先,生成一個請求對象---HttpGet,參數為請求的網址即URL

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

        // 生成一個HTTP用戶端對象----HttpClient

        HttpClient httpClient = new DefaultHttpClient();

        // 使用HTTP用戶端發送請求對象

        // 得到伺服器端發送響應的内容---通過inputStream

        InputStream inputStream = null;

        try {

          // 伺服器端發送的響應----httpResponse

          httpResponse = httpClient.execute(httpGet);

          // 伺服器端發送響應的内容---httpEntity

          httpEntity = httpResponse.getEntity();

          // 得到伺服器端發送響應的内容---通過inputStream

          inputStream = httpEntity.getContent();

          // IO流的操作

          BufferedReader bufferedReader = new BufferedReader(

              new InputStreamReader(inputStream));

          String result = "";

          String line = "";

          while ((line = bufferedReader.readLine()) != null) {

            result = result + line;

          }

          System.out.println(result);

        } catch (Exception e) {

          // TODO Auto-generated catch block

          e.printStackTrace();

        } finally {

          try {

            inputStream.close();

          } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

      }

    });

  }

}

Http兩種請求的特點----Httpget和HttpPost

get請求和post請求的差別在于:

get在向伺服器端發送資料的時候需要在URL後加上?+鍵值對&鍵值對

post在向伺服器端發送資料時:如果需要發送鍵值對資料時要使用NameValurPair對象添加資料,然後在放進list對象裡去,然後通過httpEntity 對象把list放進去,再将httpEntity 對象放到httppost裡面,httppost裡面直接寫URL即可

詳細代碼參看Mars老師的android視訊,第四季Http(三)。

繼續閱讀