標籤:
套路篇
1.HttpClient是一個介面,因此無法建立它的執行個體,通常情況下都會建立一個DefaultHttpClient的執行個體
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傳入
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);
3.執行完execute()方法後會返回一個HttpResponse對象,伺服器返回的資料都在裡面,通常我們會先取出伺服器返回的狀態代碼,如果等於200,則說明請求響應成功
if(httpResponse.getStatusLine().getStatueCode()==200){ //請求和響應都成功了}
4.讀取伺服器返回的具體內容,可以調用getEntity()訪問擷取到一個HttpEntity執行個體,然後調用EntityUtils.toString()這個靜態類將HttpEntity轉換成字串
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);
如果返回的資料帶有中文,轉換的時候需要將字元集指定為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>
Android使用HTTP協議訪問網路——HttpClient