Android学习二:Http操作

1.初步认识HTTP

HTTP(Hypertext Transfer Protocol超文本传输协议)是网络应用层协议,建立在TCP/IP基础上,HTTP使用可靠的TCP连接,默认端口是80。

较常用的HTTP为GET和POST,不同在于GET通过在请求URL中设定参数来查询,POST则是以表单的形式将数据发送给web端

2.Android下HTTP操作

package org.tonny.httpUtil;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpService {
    private HttpClient _httpClient = null;
    private HttpGet _httpGet = null;
    private HttpPost _httpPost = null;

    private HttpResponse _httpResponse = null;
    private HttpEntity _responseEntity = null;
    private HttpEntity _requestEntity = null;

    public HttpService() {
        _httpClient = new DefaultHttpClient();
    }

    public String get(String url) throws Exception {
        // http请求对象
        _httpGet = new HttpGet(url);

        // 执行GET请求
        _httpResponse = _httpClient.execute(_httpGet);

        // 200表示请求成功
        if (_httpResponse.getStatusLine().getStatusCode() == 200) {
            _responseEntity = _httpResponse.getEntity();
            return EntityUtils.toString(_responseEntity);
        } else {
            return null;
        }
    }

    /**
     * 
     * @param url
     *            请求的URL地址
     * @param params
     *            POST的参数,使用键值对的方式传入
     * @return
     * @throws Exception
     */
    public String post(String url, List<NameValuePair> params) throws Exception {
        _httpPost = new HttpPost(url);
        
        //注意这里需要请求实体
        _requestEntity = new UrlEncodedFormEntity(params);
        _httpPost.setEntity(_requestEntity);
        _httpResponse = _httpClient.execute(_httpPost);
        if (_httpResponse.getStatusLine().getStatusCode() == 200) {
            
            //数据返回还是使用实体
            _responseEntity = _httpResponse.getEntity();
            return EntityUtils.toString(_responseEntity);
        } else {
            return null;
        }
    }
}

这里封装了POST和GET请求,这里只处理了返回字符形式的,对于字节形式(如图片文件)还需要修改一下

package org.tonnny.httptest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.tonny.httpUtil.HttpService;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {
    private EditText _txtUrl = null;
    private TextView _lblInfo = null;
    private Handler _handler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this._txtUrl = (EditText) this.findViewById(R.id.txtUrl);
        this._lblInfo = (TextView) this.findViewById(R.id.lblInfo);

        // 这里使用handler实现work线程和UI线程的通信,主要是work线程向UI发送消息,所以在这里定了了消息的处理方法
        this._handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String content = String.valueOf(msg.obj);
                Log.d("Main in UI ", content);
                _lblInfo.setText(content);
            }
        };
    }

    /**
     * 这里没有采用定义类的方式,而是直接在activity_main中定义onclick属性来实现
     * @param v
     */
    public void OnBtnGetClick(View v) {
        // String url = this._txtUrl.getText().toString().trim();
        String url = "http://www.baidu.com";
        GetThread work = new GetThread(url);
        work.start();
    }

    /**
     * 这里POST的参数需要设置好
     * @param v
     */
    public void OnBtnPostClick(View v) {
        // String url = this._txtUrl.getText().toString().trim();
        String url = "http://mail.163.com/";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("savelogin", "0"));
        params.add(new BasicNameValuePair("url2",
                "http://mail.163.com/errorpage/error163.htm"));
        params.add(new BasicNameValuePair("username", "***"));
        params.add(new BasicNameValuePair("passowrd", "***"));
        PostThread work = new PostThread(url, params);
        work.start();
    }

    /**
     * Get work线程类
     * @author Tinny Cheung
     *
     */
    private final class GetThread extends Thread {
        private String _url;

        public GetThread(String url) {
            _url = url;
        }

        @Override
        public void run() {
            HttpService getMethod = new HttpService();
            try {
                String res = getMethod.get(_url);
                Message msg = _handler.obtainMessage();
                msg.obj = res;
                _handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Post work线程类
     * @author Tinny Cheung
     *
     */
    private final class PostThread extends Thread {
        private String _url;
        private List<NameValuePair> _params;

        public PostThread(String url, List<NameValuePair> params) {
            _url = url;
            _params = params;
        }

        @Override
        public void run() {
            HttpService postMethod = new HttpService();
            try {
                String res = postMethod.post(_url, _params);
                Message msg = _handler.obtainMessage();
                msg.obj = res;
                _handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

这里实现对上面封装类的使用,由于邮箱涉及个人隐私问题,所以没有写上去。读者可以通过Http Analyzer之类的工具简单的分析就可以获取到相关的数据。

另外要说的是,此处设计用到了线程间的通信,使用的loop-handler方法来实现,具体细节代码中已有体现。最后记得在清单文件加入许可,如下:

<uses-permission android:name="android.permission.INTERNET"/>

 

3.总结

个人觉得以后项目中Http的操作肯定是比较多的,与具体的业务结合起来,那还是相当复杂,这一块还是要重点掌握,多学多练。事情要做好还有很需要下一番功夫,哎,我就是这样一个懒散的人,以后再完善吧。

 

posted @ 2015-04-09 02:36  oneqhw  阅读(223)  评论(0编辑  收藏  举报