HttpClient 用法
- Socket
- HTTP
- HttpURLConnection
- HttpClient
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();
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。