public interface
HttpClient
org.apache.http.client.HttpClient |
HttpClient是Apache提供的Http网络访问接口。
1、创建HttpClient实例
HttpClient是一个接口,无法直接创建实例,通常创建一个DefaultHttpClient(HttpClient 的SubClass)实例。
HttpClient httpClient = new DefaultHttpClient();
2、如果想要发起一条GET请求 ,可以创建一个HttpGet对象,传入目标地址,之后调用HttpClient的execute()方法
HttpGet = new HttpClient("http://www.baidu.com");
httpClient.execute(httpGet);
3、执行execute()后,会返回一个HttpResponse对象,服务器返回的所有信息都在这里面,通常都会先取出服务器返回的状态吗,若等于200则说明请求和相应都成功了
if(httpResponse.getStatusLine().getStatusCode() == 200){
}
接下来在这个if判断内部取出服务返回的具体内容,可以调用httpResponse getEntity()获得一个HttpEntity实例,再调用EntityUtils.toString这个静态方法将HttpEntity转换成字符串
HttpEntity httpEntity = httpResponse.getEntity();
String responseString = EntityUtils.toString(httpEntity,"utf-8");
//将服务器返回的结果存放到Message对象中
Message message = Message.obtain(mHandler, SEND_REQUEST, responseString);
mHandler.sendMessage(message);
Handler mHandler = new Handler(){@Overridepublic void handleMessage(Message msg){if(msg.what == SEND_REQUEST){String response = (String)msg.obj;responseTextView.setText(response);}}};
主要代码:
public class MainActivity extends ActionBarActivity implements OnClickListener{private Button sendRequestBtn;private TextView responseTextView;private int SEND_REQUEST = 0;Handler mHandler = new Handler(){@Overridepublic void handleMessage(Message msg){if(msg.what == SEND_REQUEST){String response = (String)msg.obj;responseTextView.setText(response);}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);sendRequestBtn = (Button)findViewById(R.id.requestBtn);responseTextView = (TextView)findViewById(R.id.responseText);sendRequestBtn.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(v.getId() == R.id.requestBtn){sendRequestWithHttpClient();}}private void sendRequestWithHttpClient(){new Thread(new Runnable(){@Overridepublic 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 httpEntity = httpResponse.getEntity();String responseString = EntityUtils.toString(httpEntity,"utf-8");//将服务器返回的结果存放到Message对象中Message message = Message.obtain(mHandler, SEND_REQUEST, responseString);mHandler.sendMessage(message);}}catch(Exception e){e.printStackTrace();}}}).start();}}
完整代码在:https://github.com/HiSunny/ComeOnHttpClient.git