Android使用Apache HttpClient發送GET、POST請求

來源:互聯網
上載者:User

簡單的網頁下載,HttpURLConnection可以完成,但是涉及到使用者登入等許可權相關問題,就需要涉及Session、Cookies。,就很難使用HttpURLConnection來處理了。Apache開源組織提供了一個HttpClient項目可以處理這些問題。HttpClient關注於如何發送請求、接受請求,以及管理HTTP連結。
使用HttpClient對象來發送請求、接受響應步驟:


建立HttpClient對象
如果要發送GET請求,建立HttpGet對象;如果是POST請求,則建立HttpPost對象。
如果需要添加參數,對於HttpGet直接在構造URL的時候填入參數。對於POST請求,使用setEntity(HttpEntity entity)方法來設定
調用HttpClient對象的execute(HttpUriRequest request)發送請求,此方法返回一個HttpResponse
調用HttpResponse的getALLHeaders()、getHeaders(String name)等方法可擷取伺服器回應標頭;調用HttpResponse的getEntity()方法可擷取HttpEntity對象,該對象封裝了伺服器響應內容。
注意:


不少地方說可以使用HttpGet和HttpPost共同的setParams(HttpParams params)方法添加請求參數,但是我沒有設定成功,網上搜尋發現好多人也沒成功。Even Apache’s official example uses URIBuilder’s setParameter method to build the params out in the URI,所以沒有使用這種方法.


GET請求Demo:

public class MainActivity extends Activity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView textViewShow = (TextView) findViewById(R.id.showText);        //直接在URL後添加請求參數        String url = "http://192.168.1.103/index.php?get1=hello&get2=bay";        try {            // 建立DefaultHttpClient對象            HttpClient httpclient = new DefaultHttpClient();            // 建立一個HttpGet對象            HttpGet get = new HttpGet(url);            // 擷取HttpResponse對象            HttpResponse response = httpclient.execute(get);            //判斷是否連結成功            if (response.getStatusLine().getStatusCode() == 200) {                //實體轉換為字串                String content = EntityUtils.toString(response.getEntity(),"utf-8");                textViewShow.setText(content);            }else{                textViewShow.setText("網路錯誤");            }         } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }     @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }}
POST請求Demo:

public class MainActivity extends Activity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView textViewShow = (TextView) findViewById(R.id.showText);         String url = "http://192.168.1.103/index.php";        HttpClient httpClient = new DefaultHttpClient();        try {        HttpPost post = new HttpPost(url);        List params = new ArrayList();        params.add(new BasicNameValuePair("get1", "hello"));        params.add(new BasicNameValuePair("get2", "usrl"));             post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));            HttpResponse response = httpClient.execute(post);            if(response.getStatusLine().getStatusCode() ==200){                String content = EntityUtils.toString(response.getEntity(),"utf-8");                textViewShow.setText(content);             }else{                textViewShow.setText("網路問題");            }         } catch (UnsupportedEncodingException e) {            // TODO Auto-generated catch block            textViewShow.setText("UnsupportedEncodingException");        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            textViewShow.setText("ClientProtocolException");        } catch (IOException e) {            // TODO Auto-generated catch block            textViewShow.setText("IOException");        }     }     @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    } }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.