Android--httpclient類比post請求和get請求分析

來源:互聯網
上載者:User

Android--httpclient類比post請求和get請求分析

HttpClient的使用模式:

1. 建立一個HttpClent

2.執行個體化新的HTTP方法,比如PostMethod 或 GetMethod

3.設定HTTP參數名稱/值

4.使用HttpClent執行HTTP調用

5.處理Http響應

 

import java.io.IOException;import java.io.InputStream;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.StatusLine;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import com.itheima.httpclient.utils.Utils;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {Handler handler = new Handler(){@Overridepublic void handleMessage(android.os.Message msg) {Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();}};    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    //get方法    public void get(View v){    EditText et_name = (EditText) findViewById(R.id.et_name);    EditText et_pass = (EditText) findViewById(R.id.et_pass);        final String name = et_name.getText().toString();    final String pass = et_pass.getText().toString();            Thread t = new Thread(){    @Override    public void run() {    String path = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;        //使用httpClient架構做get方式提交        //1.建立HttpClient對象        HttpClient hc = new DefaultHttpClient();                //2.建立httpGet對象,構造方法的參數就是網址        HttpGet hg = new HttpGet(path);                //3.使用用戶端對象,把get請求對象發送出去        try {    HttpResponse hr = hc.execute(hg);    //拿到回應標頭中的狀態行    StatusLine sl = hr.getStatusLine();    if(sl.getStatusCode() == 200){    //拿到回應標頭的實體    HttpEntity he = hr.getEntity();    //拿到實體中的內容,其實就是伺服器返回的輸入資料流    InputStream is = he.getContent();    String text = Utils.getTextFromStream(is);        //發送訊息,讓主線程重新整理ui顯示text    Message msg = handler.obtainMessage();    msg.obj = text;    handler.sendMessage(msg);    }    } catch (Exception e) {    // TODO Auto-generated catch block    e.printStackTrace();    }    }    };    t.start();        }    //post方法    public void post(View v){    EditText et_name = (EditText) findViewById(R.id.et_name);    EditText et_pass = (EditText) findViewById(R.id.et_pass);        final String name = et_name.getText().toString();    final String pass = et_pass.getText().toString();        Thread t = new Thread(){    @Override    public void run() {    String path = "http://192.168.13.13/Web/servlet/CheckLogin";        //1.建立用戶端對象        HttpClient hc = new DefaultHttpClient();        //2.建立post請求對象        HttpPost hp = new HttpPost(path);                //封裝form表單提交的資料        BasicNameValuePair bnvp = new BasicNameValuePair("name", name);        BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);        List parameters = new ArrayList();        //把BasicNameValuePair放入集合中        parameters.add(bnvp);        parameters.add(bnvp2);                try {        //要提交的資料都已經在集合中了,把集合傳給實體物件        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");        //設定post請求對象的實體,其實就是把要提交的資料封裝至post請求的輸出資料流中        hp.setEntity(entity);        //3.使用用戶端發送post請求    HttpResponse hr = hc.execute(hp);    if(hr.getStatusLine().getStatusCode() == 200){    InputStream is = hr.getEntity().getContent();    String text = Utils.getTextFromStream(is);        //發送訊息,讓主線程重新整理ui顯示text    Message msg = handler.obtainMessage();    msg.obj = text;    handler.sendMessage(msg);    }    } catch (Exception e) {    // TODO Auto-generated catch block    e.printStackTrace();    }    }    };    t.start();        }}
Utils方法:

 

 

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class Utils {public static String getTextFromStream(InputStream is){byte[] b = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();try {while((len = is.read(b)) != -1){bos.write(b, 0, len);}String text = new String(bos.toByteArray());bos.close();return text;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}



 

 

聯繫我們

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