天天看點

Android:HttpURLConnection接口

Android:HttpURLConnection接口

      在Http通信中,我們使用POST和GET請求方式進行通信。GET可以獲得靜态頁面,也可以把參數放在URL字元串後面,傳遞給伺服器。而POST方法的參數是放在Http請求中。是以,在程式設計之前,應當首先明确使用的請求方法,然後再根據所使用的方式選擇相應的程式設計方式。

      HttpURLConnection是繼承于URLConnection類,二者都是抽象類。其對象主要通過URL的openConnection方法獲得。建立方法如下代碼所示:

Java代碼

URL url = new URL("http://www.51cto.com/index.jsp?par=123456");    

HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();  

URL url = newURL("http://www.51cto.com/index.jsp?par=123456"); 

HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();

    通過以下方法可以對請求的屬性進行一些設定,如下所示

Java代碼

//設定輸入和輸出流    

urlConn.setDoOutput(true);     

urlConn.setDoInput(true);     

//設定請求方式為POST    

urlConn.setRequestMethod("POST");    

//POST請求不能使用緩存    

urlConn.setUseCaches(false);    

//關閉連接配接    

urlConn.disConnection();   

//設定輸入和輸出流 

urlConn.setDoOutput(true); 

urlConn.setDoInput(true); 

//設定請求方式為POST 

urlConn.setRequestMethod("POST"); 

//POST請求不能使用緩存 

urlConn.setUseCaches(false);

//關閉連接配接 

urlConn.disConnection();

Manifest檔案中權限的設定:

Xml代碼

<uses-permission android:name="android.permission.INTERNET" />   

<uses-permissionandroid:name="android.permission.INTERNET" />

HttpURLConnection預設使用GET方式,例如下面代碼所示:

Java代碼

//以Get方式上傳參數   

public class Activity03 extends Activity  

{   

    private final String DEBUG_TAG = "Activity03";   

    @Override  

    public void onCreate(Bundle savedInstanceState)  

    {   

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.http);    

        TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);  

        //http位址"?par=abcdefg"是我們上傳的參數   

        String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdefg";  

        //獲得的資料   

        String resultData = "";  

        URL url = null;  

        try  

        {  

            //構造一個URL對象   

            url = new URL(httpUrl);   

        }  

        catch (MalformedURLException e)  

        {  

            Log.e(DEBUG_TAG, "MalformedURLException");  

        }  

        if (url != null)  

        {  

            try  

            {  

                // 使用HttpURLConnection打開連接配接  

                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  

                //得到讀取的内容(流)   

                InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  

                // 為輸出建立BufferedReader   

                BufferedReader buffer = new BufferedReader(in);  

                String inputLine = null;  

                //使用循環來讀取獲得的資料   

                while (((inputLine = buffer.readLine()) != null))  

                {  

                    //我們在每一行後面加上一個"\n"來換行  

                    resultData += inputLine + "\n";  

                }           

                //關閉InputStreamReader   

                in.close();  

                //關閉http連接配接   

                urlConn.disconnect();  

                //設定顯示取得的内容   

                if ( resultData != null )  

                {  

                    mTextView.setText(resultData);  

                }  

                else   

                {  

                    mTextView.setText("讀取的内容為NULL");   

                }  

            }  

            catch (IOException e)  

            {  

                Log.e(DEBUG_TAG, "IOException");  

            }  

        }  

        else  

        {  

            Log.e(DEBUG_TAG, "Url NULL");  

        }   

}  

//以Get方式上傳參數

public class Activity03 extendsActivity

{

  private final String DEBUG_TAG = "Activity03";

  @Override

  public void onCreate(Bundle savedInstanceState)

  {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.http); 

    TextView mTextView =(TextView)this.findViewById(R.id.TextView_HTTP);

    //http位址"?par=abcdefg"是我們上傳的參數

    String httpUrl ="http://192.168.1.110:8080/httpget.jsp?par=abcdefg";

    //獲得的資料

    String resultData = "";

    URL url = null;

    try

    {

      //構造一個URL對象

      url = new URL(httpUrl);

    }

    catch (MalformedURLException e)

    {

      Log.e(DEBUG_TAG, "MalformedURLException");

    }

    if (url != null)

    {

      try

      {

        // 使用HttpURLConnection打開連接配接

        HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

        //得到讀取的内容(流)

        InputStreamReader in = newInputStreamReader(urlConn.getInputStream());

        // 為輸出建立BufferedReader

        BufferedReader buffer = new BufferedReader(in);

        String inputLine = null;

        //使用循環來讀取獲得的資料

        while (((inputLine = buffer.readLine()) != null))

        {

          //我們在每一行後面加上一個"\n"來換行

          resultData += inputLine + "\n";

        }     

        //關閉InputStreamReader

        in.close();

        //關閉http連接配接

        urlConn.disconnect();

        //設定顯示取得的内容

        if ( resultData != null )

        {

          mTextView.setText(resultData);

        }

        else

        {

          mTextView.setText("讀取的内容為NULL");

        }

      }

      catch (IOException e)

      {

        Log.e(DEBUG_TAG, "IOException");

      }

    }

    else

    {

      Log.e(DEBUG_TAG, "Url NULL");

    }

}

  如果需要使用POST方式,則需要setRequestMethod設定。代碼如下:

Java代碼

//以post方式上傳參數   

public class Activity04  extends Activity  

{   

    private final String DEBUG_TAG = "Activity04";   

    @Override  

    public void onCreate(Bundle savedInstanceState)  

    {   

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.http);  

        TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);  

        //http位址"?par=abcdefg"是我們上傳的參數   

        String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  

        //獲得的資料   

        String resultData = "";  

        URL url = null;  

        try  

        {  

            //構造一個URL對象   

            url = new URL(httpUrl);   

        }  

        catch (MalformedURLException e)  

        {  

            Log.e(DEBUG_TAG, "MalformedURLException");  

        }  

        if (url != null)  

        {  

            try  

            {  

                // 使用HttpURLConnection打開連接配接  

                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  

                //因為這個是post請求,設立需要設定為true   

                urlConn.setDoOutput(true);  

                urlConn.setDoInput(true);  

                // 設定以POST方式   

                urlConn.setRequestMethod("POST");  

                // Post 請求不能使用緩存   

                urlConn.setUseCaches(false);  

                urlConn.setInstanceFollowRedirects(true);  

                // 配置本次連接配接的Content-type,配置為application/x-www-form-urlencoded的   

                urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  

                // 連接配接,從postUrl.openConnection()至此的配置必須要在connect之前完成,   

                // 要注意的是connection.getOutputStream會隐含的進行connect。   

                urlConn.connect();  

                //DataOutputStream流   

                DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  

                //要上傳的參數   

                String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");  

                //将要上傳的内容寫入流中   

                out.writeBytes(content);   

                //重新整理、關閉   

                out.flush();  

                out.close();   

                //擷取資料   

                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  

                String inputLine = null;  

                //使用循環來讀取獲得的資料   

                while (((inputLine = reader.readLine()) != null))  

                {  

                    //我們在每一行後面加上一個"\n"來換行  

                    resultData += inputLine + "\n";  

                }           

                reader.close();  

                //關閉http連接配接   

                urlConn.disconnect();  

                //設定顯示取得的内容   

                if ( resultData != null )  

                {  

                    mTextView.setText(resultData);  

                }  

                else   

                {  

                    mTextView.setText("讀取的内容為NULL");   

                }  

            }  

            catch (IOException e)  

            {  

                Log.e(DEBUG_TAG, "IOException");  

            }  

        }  

        else  

        {  

            Log.e(DEBUG_TAG, "Url NULL");  

        }   

    }   

}  

//以post方式上傳參數

public class Activity04  extends Activity

{

  private final String DEBUG_TAG = "Activity04";

  @Override

  public void onCreate(Bundle savedInstanceState)

  {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.http);

    TextView mTextView =(TextView)this.findViewById(R.id.TextView_HTTP);

    //http位址"?par=abcdefg"是我們上傳的參數

    String httpUrl ="http://192.168.1.110:8080/httpget.jsp";

    //獲得的資料

    String resultData = "";

    URL url = null;

    try

    {

      //構造一個URL對象

      url = new URL(httpUrl);

    }

    catch (MalformedURLException e)

    {

      Log.e(DEBUG_TAG, "MalformedURLException");

    }

    if (url != null)

    {

      try

      {

        // 使用HttpURLConnection打開連接配接

        HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

        //因為這個是post請求,設立需要設定為true

        urlConn.setDoOutput(true);

        urlConn.setDoInput(true);

            // 設定以POST方式

        urlConn.setRequestMethod("POST");

            // Post 請求不能使用緩存

        urlConn.setUseCaches(false);

        urlConn.setInstanceFollowRedirects(true);

            // 配置本次連接配接的Content-type,配置為application/x-www-form-urlencoded的

        urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

            // 連接配接,從postUrl.openConnection()至此的配置必須要在connect之前完成,

            // 要注意的是connection.getOutputStream會隐含的進行connect。

        urlConn.connect();

        //DataOutputStream流

            DataOutputStreamout = new DataOutputStream(urlConn.getOutputStream());

            //要上傳的參數

            String content ="par=" + URLEncoder.encode("ABCDEFG", "gb2312");

            //将要上傳的内容寫入流中

           out.writeBytes(content);

            //重新整理、關閉

            out.flush();

            out.close();

            //擷取資料

            BufferedReaderreader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        String inputLine = null;

        //使用循環來讀取獲得的資料

        while (((inputLine = reader.readLine()) != null))

        {

          //我們在每一行後面加上一個"\n"來換行

          resultData += inputLine + "\n";

        }     

        reader.close();

        //關閉http連接配接

        urlConn.disconnect();

        //設定顯示取得的内容

        if ( resultData != null )

        {

          mTextView.setText(resultData);

        }

        else

        {

          mTextView.setText("讀取的内容為NULL");

        }

      }

      catch (IOException e)

      {

        Log.e(DEBUG_TAG, "IOException");

      }

    }

    else

    {

      Log.e(DEBUG_TAG, "Url NULL");

    }

  }

}

 Android:HttpClient接口

 使用Apache提供的HttpClient接口同樣可以進行HTTP操作。

 對于GET和POST請求方法的操作有所不同。GET方法的操作代碼示例如下:

Java代碼

public class Activity02 extends Activity  

{   

    @Override  

    public void onCreate(Bundle savedInstanceState)  

    {   

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.http);  

        TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);  

        // http位址   

        String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  

        //HttpGet連接配接對象   

        HttpGet httpRequest = new HttpGet(httpUrl);  

        try  

        {  

            //取得HttpClient對象   

            HttpClient httpclient = new DefaultHttpClient();  

            //請求HttpClient,取得HttpResponse  

            HttpResponse httpResponse = httpclient.execute(httpRequest);  

            //請求成功   

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  

            {  

                //取得傳回的字元串   

                String strResult = EntityUtils.toString(httpResponse.getEntity());  

                mTextView.setText(strResult);  

            }  

            else  

            {  

                mTextView.setText("請求錯誤!");   

            }  

        }  

        catch (ClientProtocolException e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }  

        catch (IOException e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }  

        catch (Exception e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }    

            }  

}  

public class Activity02 extendsActivity

{

  @Override

  public void onCreate(Bundle savedInstanceState)

  {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.http);

    TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);

    // http位址

    String httpUrl ="http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";

    //HttpGet連接配接對象

    HttpGet httpRequest = new HttpGet(httpUrl);

    try

    {

      //取得HttpClient對象

      HttpClient httpclient = new DefaultHttpClient();

      //請求HttpClient,取得HttpResponse

      HttpResponse httpResponse = httpclient.execute(httpRequest);

      //請求成功

      if (httpResponse.getStatusLine().getStatusCode() ==HttpStatus.SC_OK)

      {

        //取得傳回的字元串

        String strResult = EntityUtils.toString(httpResponse.getEntity());

        mTextView.setText(strResult);

      }

      else

      {

        mTextView.setText("請求錯誤!");

      }

    }

    catch (ClientProtocolException e)

    {

      mTextView.setText(e.getMessage().toString());

    }

    catch (IOException e)

    {

      mTextView.setText(e.getMessage().toString());

    }

    catch (Exception e)

    {

      mTextView.setText(e.getMessage().toString());

    } 

      }

}

  使用POST方法進行參數傳遞時,需要使用NameValuePair來儲存要傳遞的參數,另外,還需要設定所使用的字元集。代碼如下所示:

Java代碼

public class Activity03 extends Activity  

{   

    @Override  

    public void onCreate(Bundle savedInstanceState)  

    {   

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.http);  

        TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);  

        // http位址   

        String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  

        //HttpPost連接配接對象   

        HttpPost httpRequest = new HttpPost(httpUrl);  

        //使用NameValuePair來儲存要傳遞的Post參數   

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

        //添加要傳遞的參數   

        params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));  

        try  

        {  

            //設定字元集   

            HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  

            //請求httpRequest   

            httpRequest.setEntity(httpentity);  

            //取得預設的HttpClient   

            HttpClient httpclient = new DefaultHttpClient();  

            //取得HttpResponse   

            HttpResponse httpResponse = httpclient.execute(httpRequest);  

            //HttpStatus.SC_OK表示連接配接成功   

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  

            {  

                //取得傳回的字元串   

                String strResult = EntityUtils.toString(httpResponse.getEntity());  

                mTextView.setText(strResult);  

            }  

            else  

            {  

                mTextView.setText("請求錯誤!");   

            }  

        }  

        catch (ClientProtocolException e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }  

        catch (IOException e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }  

        catch (Exception e)  

        {  

            mTextView.setText(e.getMessage().toString());  

        }    

    }   

}  

public class Activity03 extendsActivity

{

  @Override

  public void onCreate(Bundle savedInstanceState)

  {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.http);

    TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);

    // http位址

    String httpUrl = "http://192.168.1.110:8080/httpget.jsp";

    //HttpPost連接配接對象

    HttpPost httpRequest = new HttpPost(httpUrl);

    //使用NameValuePair來儲存要傳遞的Post參數

    List<NameValuePair> params = newArrayList<NameValuePair>();

    //添加要傳遞的參數

    params.add(new BasicNameValuePair("par","HttpClient_android_Post"));

    try

    {

      //設定字元集

      HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");

      //請求httpRequest

      httpRequest.setEntity(httpentity);

      //取得預設的HttpClient

      HttpClient httpclient = new DefaultHttpClient();

      //取得HttpResponse

      HttpResponse httpResponse = httpclient.execute(httpRequest);

      //HttpStatus.SC_OK表示連接配接成功

      if (httpResponse.getStatusLine().getStatusCode() ==HttpStatus.SC_OK)

      {

        //取得傳回的字元串

        String strResult =EntityUtils.toString(httpResponse.getEntity());

        mTextView.setText(strResult);

      }

      else

      {

        mTextView.setText("請求錯誤!");

      }

    }

    catch (ClientProtocolException e)

    {

      mTextView.setText(e.getMessage().toString());

    }

    catch (IOException e)

    {

      mTextView.setText(e.getMessage().toString());

    }

    catch (Exception e)

    {

      mTextView.setText(e.getMessage().toString());

    } 

  }

}

     HttpClient實際上是對Java提供方法的一些封裝,在HttpURLConnection中的輸入輸出流操作,在這個接口中被統一封裝成了HttpPost(HttpGet)和HttpResponse,這樣,就減少了操作的繁瑣性。本文節選自上海Android教育訓練學校課程。