package com.example.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
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.net.http.HttpResponseCache;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
private HttpResponse httpresponse=null;//创建HttpResponse 对象
private HttpEntity httpentity=null; //创建HttpEntity对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpGet httpget=new HttpGet("http://www.baidu.com"); //创建HttpGet对象 并使用构造方法传入URL
HttpClient httpclient=new DefaultHttpClient(); //创建HttpClient对象 注意HttpClient是接口不能实例化 需要已实现接口的子类实例化
InputStream input=null; //输入流
try {
httpresponse=httpclient.execute(httpget); //httpclient执行get请求 返回Httpresponse类对象
httpentity=httpresponse.getEntity(); //httpresponse对象调用getEntity()方法获取entity
input=httpentity.getContent(); //httpentity使用getContent()方法获取输入流
BufferedReader br=new BufferedReader(new InputStreamReader(input));//读写操作
String line=null;
String content=null;
while((line=br.readLine())!=null)
{
content+=line;
}
System.out.println(content);
br.close(); //关闭流
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注意:1 要导入jar包
2.需要打开INTERNET权限