HttpClient 用法

Android的网络通信的方式有两种:
  1. Socket
  2. HTTP
而其中,HTTP又包括两种编程方式:
  1. HttpURLConnection
  2. 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不同,其他部分的代码都是相同的。
 
 
 
 

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