操作步驟:
<1>
產生請求對象
HttpGet httpGet = new HttpGet("請求地址。。。。。");
<2>
產生用戶端對象
HttpClient httpClient = new DefaultHttpClient();
<3>
執行請求
HttpResponse httpResponse = httpClient.execute(httpGet);
<4>
接受響應
HttpEntity httpEntity = httpResponse.getEntity();
<5>得到資料流
InputStream inputStream = httpEntity.getContent();
注意:
要添加許可權: <uses-permission android:name="android.permission.INTERNET" />
具體實現:
package xiaosi.httpResponse;</p><p>import java.io.BufferedReader;<br />import java.io.IOException;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;</p><p>import org.apache.http.HttpEntity;<br />import org.apache.http.HttpResponse;<br />import org.apache.http.client.ClientProtocolException;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.impl.client.DefaultHttpClient;</p><p>import android.app.Activity;<br />import android.os.Bundle;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.widget.Button;<br />import android.widget.TextView;</p><p>public class HttpResponseActivity extends Activity<br />{<br />private Buttonbutton= null;<br />private TextViewtext= null;<br />private HttpResponsehttpResponse= null;<br />private HttpEntityhttpEntity= null;</p><p>@Override<br />public void onCreate(Bundle savedInstanceState)<br />{<br />super.onCreate(savedInstanceState);<br />setContentView(R.layout.main);<br />text = (TextView) findViewById(R.id.text);<br />button = (Button) findViewById(R.id.button);<br />button.setOnClickListener(new OnClickListener() {<br />@Override<br />public void onClick(View v)<br />{<br />// 產生一個請求對象,參數就是地址<br />HttpGet httpGet = new HttpGet("http://www.baidu.com");<br />// 產生Http用戶端<br />HttpClient httpClient = new DefaultHttpClient();<br />InputStream inputStream = null;<br />// 使用HTTP用戶端發送請求對象<br />try<br />{<br />// 發送請求的響應<br />httpResponse = httpClient.execute(httpGet);<br />// 代表接收的http訊息,伺服器返回的訊息都在httpEntity<br />httpEntity = httpResponse.getEntity();<br />if(httpResponse.getStatusLine().getStatusCode() == 200){<br />inputStream = httpEntity.getContent();<br />BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));<br />String result = "";<br />String line = "";<br />while ((line = reader.readLine()) != null)<br />{<br />result = result + line;<br />}</p><p>text.setText(result);<br />}<br />}<br />catch (ClientProtocolException e)<br />{<br />e.printStackTrace();<br />}<br />catch (Exception e)<br />{<br />e.printStackTrace();<br />}<br />finally<br />{<br />try<br />{<br />inputStream.close();<br />}<br />catch (IOException e)<br />{<br />e.printStackTrace();<br />}<br />}<br />}<br />});<br />}<br />}<br />