操作步骤:
<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" />
附(其他资料地址):http://www.ibm.com/developerworks/cn/opensource/os-httpclient/
http://www.2cto.com/kf/201203/124956.html
具体实现:
package xiaosi.httpResponse;
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.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpResponseActivity extends Activity
{
private Buttonbutton = null;
private TextViewtext = null;
private HttpResponsehttpResponse = null;
private HttpEntityhttpEntity = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
// 生成一个请求对象,参数就是地址
HttpGet httpGet = new HttpGet("http://www.baidu.com");
// 生成Http客户端
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
// 使用HTTP客户端发送请求对象
try
{
// 发送请求的响应
httpResponse = httpClient.execute(httpGet);
// 代表接收的http消息,服务器返回的消息都在httpEntity
httpEntity = httpResponse.getEntity();
if(httpResponse.getStatusLine().getStatusCode() == 200){
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while ((line = reader.readLine()) != null)
{
result = result + line;
}
text.setText(result);
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
}