Android使用HTTP協議訪問網絡——HttpClient

套路篇android

1.HttpClient是一個接口,所以沒法建立它的實例,一般狀況下都會建立一個DefaultHttpClient的實例apache

HttpClient httpClient=new DefaultHttpClient();

2.若是想要發起一條GET請求,就建立一個HttpGet對象,並傳入目標網絡的對象,而後調用HtttpClient中的excute()方法:服務器

HttpGet httpGet=new HttpGet("http://www.baidu.com");
HttpResponse httpResponse=httpClient.execute(httpGet);

若是想發起一條POST請求會比GET複雜一點,首先建立一個HttpPost對象,並傳入目標網址網絡

HttpPost httpPost=new HttpPost("http/:www.baidu.com");

而後經過NameValuePair集合來存放待提交的數據,並將這個參數傳入到一個UrlEncodedFormEntity中,而後調用HttpPost的setEntity()方法將構建好的UrlEncodedFormEntity傳入app

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

params.add(new BasicNameValuePair("username","admin"));

params.add(new BasicNameValuepair("password","123456"));

UrlEncodeFormEntity entity=new UrlEncodeFormEntity(params,"utf-8");

httpPost.setEntity(entity);

接下來就和GET方法同樣啦,httpClient.execute(httpPost);ide

3.執行完execute()方法後會返回一個HttpResponse對象,服務器返回的數據都在裏面,一般咱們會先取出服務器返回的狀態碼,若是等於200,則說明請求響應成功this

if(httpResponse.getStatusLine().getStatueCode()==200){

  //請求和響應都成功了

}

4.讀取服務器返回的具體內容,能夠調用getEntity()訪問獲取到一個HttpEntity實例,而後調用EntityUtils.toString()這個靜態類將HttpEntity轉換成字符串spa

HttpEntity entity=httpResponse.getEntity();code

String response=EntityUtils.toString(entity);orm

若是返回的數據帶有中文,轉換的時候須要將字符集指定爲utf-8

String response=EntityUtils.toString(entity,"utf-8");

實戰篇

MainActivity

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    public static final int SHOW_RESPONSE=0;//用於更新操做
    private Button sendRequest_Button;
    private TextView responseText;




    //用於處理和發送消息的Handler
    private Handler handler=new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case SHOW_RESPONSE:
                    String response=(String)msg.obj;
                    responseText.setText(response);
            }
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRequest_Button=(Button)findViewById(R.id.sendrequest);
        responseText=(TextView)findViewById(R.id.response_text);
        sendRequest_Button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.sendrequest){
            sendRequestWithHttpClient();
        }
    }

    public void sendRequestWithHttpClient(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    HttpClient httpClient=new DefaultHttpClient();
                    HttpGet httpGet=new HttpGet("http://www.baidu.com");
                    HttpResponse httpResponse=httpClient.execute(httpGet);
                    if(httpResponse.getStatusLine().getStatusCode()==200){
                        //請求和響應都成功了
                        HttpEntity entity=httpResponse.getEntity();
                        String response= EntityUtils.toString(entity, "utf-8");

                        Message message=new Message();
                        message.what=SHOW_RESPONSE;
                        //將服務器返回的結果保存到Message中
                        message.obj=response.toString();
                        handler.sendMessage(message);

                    }

                }catch(Exception e){

                }finally {

                }

            }
        }).start();

    }

}

AndroidManifest

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

Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/sendrequest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>
相關文章
相關標籤/搜索