android之HttpClient

來源:互聯網
上載者:User

標籤:

Apache包是對android連網訪問封裝的很好的一個包,也是android訪問網路最常用的類。

下面分別講一下怎麼用HttpClient實現get,post請求。

1.Get 請求

HttpGet get = new HttpGet("http://www.baidu.com");HttpClient hClient = new DefaultHttpClient();httpResponse = hClient.execute(get);

  

2.Post 請求

Map<String, String> map = new HashMap<String, String>();map.put("id", id);map.put("name", name);map.put("permission", String.valueOf(permission)); List<NameValuePair> list = new ArrayList<NameValuePair>(); if(map != null && !map.isEmpty()){ for(Map.Entry<String, String> entry : map.entrySet()){//迭代器 //索引值對 NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue()); list.add(nameValuePair); } }UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);//使用post方式提交資料HttpPost post = new HttpPost(path);post.setEntity(entity);//請求體中//預設用戶端HttpClient client = httpClient;HttpResponse httpResponse = client.execute(post);

  

3.代碼執行個體:

先是get請求

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.ClientProtocolException;  import org.apache.http.client.HttpClient;  import org.apache.http.client.methods.HttpGet;  import org.apache.http.impl.DefaultHttpClientConnection;  import org.apache.http.impl.client.DefaultHttpClient;    import android.app.Activity;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;    public class MainActivity extends Activity {        private Button requestButton;      private HttpResponse httpResponse;      private HttpEntity entity;      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          requestButton = (Button) findViewById(R.id.requestButton);                    requestButton.setOnClickListener(new OnClickListener() {                            public void onClick(View v) {                   new Thread(new Downtest()).start();              }          });      }     class Downtest implements Runnable{          public void run() {          //產生一個請求對象,請求              HttpGet get = new HttpGet("http://www.baidu.com");              //產生一個Http用戶端對象              HttpClient hClient = new DefaultHttpClient();              //使用Http用戶端發送請求對象              InputStream inputStream = null;              try {                  httpResponse = hClient.execute(get);//httpResponse返回的響應                //返回的響應資料就放在裡邊                                  entity = httpResponse.getEntity();                  inputStream = entity.getContent();                  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));                  String result = "";                  String line = "";                 while((line = reader.readLine())!= null){                     result = result+ line;                 }                 System.out.println(result);              } catch (ClientProtocolException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              } catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }finally{                  try{                      inputStream.close();                  }catch(Exception e){                      e.printStackTrace();                  }              }       }     }        }  

  再是post請求

public class AccountHttpUtils {        //private static String PATH = "http://192.168.253.1:8088/CallName/servlet/AccountServler";      private static HttpClient httpClient;      public AccountHttpUtils(HttpClient httpClient) {             this.httpClient = httpClient;      }     public static String sendHttpClient(String path,Map<String,String> map,String encode){        List<NameValuePair> list = new ArrayList<NameValuePair>();        if(map != null && !map.isEmpty()){            for(Map.Entry<String, String> entry : map.entrySet()){//迭代器                //索引值對                NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());                list.add(nameValuePair);            }        }        try {            //實現將請求的參數封裝到表單中,          UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);          //使用post方式提交資料          HttpPost post = new HttpPost(path);          post.setEntity(entity);//請求體中          //預設用戶端          HttpClient client = httpClient;                    HttpResponse httpResponse = client.execute(post);          if(httpResponse.getStatusLine().getStatusCode() == 200){              HttpEntity httpEntity = httpResponse.getEntity();              InputStream inputStream = httpEntity.getContent();              return changeInputeStream(inputStream, encode);          }      } catch (UnsupportedEncodingException e) {          // TODO Auto-generated catch block          e.printStackTrace();      } catch (ClientProtocolException e) {          // TODO Auto-generated catch block          e.printStackTrace();      } catch (IOException e) {          // TODO Auto-generated catch block          e.printStackTrace();      }                return "";     }     /**     * 將一個輸入資料流轉換成字串     * @param inputStream     * @param encode     * @return     */     private static String changeInputeStream(InputStream inputStream,String encode) {         //通常叫做記憶體流,寫在記憶體中的          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();          byte[] data = new byte[1024];          int len = 0;          String result = "";          if(inputStream != null){              try {                  while((len = inputStream.read(data))!=-1){                      data.toString();                      outputStream.write(data, 0, len);                  }                  //result是在伺服器端設定的doPost函數中的                  result = new String(outputStream.toByteArray(),encode);                  outputStream.flush();                  outputStream.close();                  inputStream.close();              } catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }          }          return result;      }      public static String set(String id,String name,int permission) {          // TODO Auto-generated method stub          Map<String, String> map = new HashMap<String, String>();          map.put("id", id);          map.put("name", name);          map.put("permission", String.valueOf(permission));          String result = AccountHttpUtils.sendHttpClient(AbstractHttpUtils.PATH+"servlet/AccountServler", map, "utf-8");          System.out.println("result:"+ result);          return result;      }    }  

  4.get請求訪問的是百度,返回的是百度首頁的原始碼

        post是我的一個小項目中的類 

       不過結構已經很清晰啦。。。。

   留著備用。。。。。。

http://www.cnblogs.com/jycboy/p/httpclient.html

android之HttpClient

聯繫我們

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