Android的网络通信的方式有两种:
- Socket
- HTTP
而其中,HTTP又包括两种编程方式:
- HttpURLConnection
- HttpClient
这篇文章介绍的就是,HttpClient
首先,依然是创建
HttpClient client = new DefaultHttpClient();
第二步,GET请求方式,获得服务器响应
HttpGet httpGet = new HttpGet("http://www.baidu.com");
httpClient.execute(httpSet);
第三步,判断返回的状态码
if(httpResponse.getStatusLine().getStatusCode()==200){
}
四步,创建HttpEntity对象,获取服务器响应
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private Button sendRequest;
private TextView responseText;
public static final int SHOW_RESPONSE = 0;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String)msg.obj;
responseText.setText(response);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.send_request) {
// sendRequestWithHttpURLConnection();
sendRequestWithHttpClient();
}
}
private void sendRequestWithHttpClient(){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = client.execute(get);
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.obj=response;
handler.sendMessage(message);
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
}
除了sendRequestWithHttpClient与之前的HttpURLConnection不同,其他部分的代码都是相同的。