Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android下通過httpClient發送GET和POST請求的實例代碼

Android下通過httpClient發送GET和POST請求的實例代碼

編輯:關於Android編程

復制代碼 代碼如下:
       public class HttpUtil {

    public static String sendDataByHttpClientGet(String path,String name,String pass){
        String result = "";
        //1.獲取到一個浏覽器
        HttpClient client = new DefaultHttpClient();
        //2.准備請求的地址
        try {
            String arg1 = URLEncoder.encode(name, "utf-8");
            String arg2 = URLEncoder.encode(pass, "utf-8");
            HttpGet httpGet = new HttpGet(path+"?name="+arg1+"&pass="+arg2);

            //3.敲回車發請求
            HttpResponse resp = client.execute(httpGet);
            //狀態碼
            int code = resp.getStatusLine().getStatusCode();
            if(code==200){
                //resp.getEntity().getContent();
                result = EntityUtils.toString(resp.getEntity(),"utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String sendDataByHttpClientPost(String path,String name,String pass){
        String result = "";
        //1獲取到一個浏覽器
        HttpClient client = new DefaultHttpClient();

        //2.准備要請求的數據類型
        HttpPost httpPost = new HttpPost(path);
        try {
            //鍵值對  NameValuePair
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name",name));
            params.add(new BasicNameValuePair("pass", pass));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
            //3.設置POST請求數據實體
            httpPost.setEntity(entity);
            //4.發送數據給服務器
            HttpResponse resp = client.execute(httpPost);
            int code = resp.getStatusLine().getStatusCode();
            if(code==200){
                result = EntityUtils.toString(resp.getEntity(),"utf-8");
            }
        } catch (Exception e) {
        }
        return result;
    }

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved