异步HTTP请求

一、自定义异步的HTTP请求

1.自定义一个AsyncHttpClient类,用于处理HTTP请求,实际原理就是新开启一个线程,调用HttpClient处理GET和POST请求

package com.shz.services;

import java.util.List;

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 android.os.Message;

public class MyAsyncHttpClient {
    
    public void get(final String url,final MyHandler handler)
    {
        new Thread(){
            public void run() {
                Message msg = new Message();
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse response = client.execute(httpGet);
                    int code = response.getStatusLine().getStatusCode();
                    if(code == 200)
                    {
                        msg.what = 1;
                        msg.obj = loginService.readInputStream(response.getEntity().getContent());
                    }
                    else
                    {
                        msg.what = 2;
                        msg.obj = "请求失败,错误码:"+code;
                    }
                    
                } catch (Exception e) {
                    msg.what = 2;
                    msg.obj = e.getMessage();
                } finally{
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }
    
    public void post(final String url,final List<NameValuePair> pairs,final MyHandler handler)
    {
        new Thread(){
            public void run() {
                Message msg = new Message();
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(url);
                    
                    if(pairs != null)
                    {
                        post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
                    }
                    
                    HttpResponse response = client.execute(post);
                    int code = response.getStatusLine().getStatusCode();
                    if(code == 200)
                    {
                        msg.what = 1;
                        msg.obj = loginService.readInputStream(response.getEntity().getContent());
                    }
                    else
                    {
                        msg.what = 2;
                        msg.obj = "请求失败,错误码:"+code;
                    }
                } catch (Exception e) {
                    msg.what = 2;
                    msg.obj = e.getMessage();
                } finally{
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }
}
View Code

2.处理服务器返回消息的MyHandler类,该类继承Handler

package com.shz.services;

import android.os.Handler;
import android.os.Message;

public class MyHandler extends Handler {
    public void onSuccess(String content) {

    }

    public void onFailure(String content) {

    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
        case 1:
            onSuccess(msg.obj.toString());
            break;
        case 2:
            onFailure(msg.obj.toString());
            break;
        default:
            break;
        }
    }

}
View Code

3.测试代码

package com.shz.login;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.shz.myasynchttp.R;
import com.shz.services.MyAsyncHttpClient;
import com.shz.services.MyHandler;

public class MainActivity extends Activity {

    private EditText txtUserName;
    private EditText txtPassword;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
        this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
    }        
    
    public void loginGet(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
                + URLEncoder.encode(userName)
                + "&Password="
                + URLEncoder.encode(password);
        
        MyAsyncHttpClient client = new MyAsyncHttpClient();
        client.get(path, new MyHandler(){

            @Override
            public void onSuccess(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }

            @Override
            public void onFailure(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }
            
        });
    }    
    
    public void loginPost(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
        MyAsyncHttpClient client = new MyAsyncHttpClient();
        // 设置要提交的数据
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("UserName", userName));
        pairs.add(new BasicNameValuePair("Password", password));
        client.post(path, pairs, new MyHandler(){

            @Override
            public void onSuccess(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }

            @Override
            public void onFailure(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }
            
        });
    }  

}
View Code

布局代码

package com.shz.login;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.shz.myasynchttp.R;
import com.shz.services.MyAsyncHttpClient;
import com.shz.services.MyHandler;

public class MainActivity extends Activity {

    private EditText txtUserName;
    private EditText txtPassword;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
        this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
    }        
    
    public void loginGet(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
                + URLEncoder.encode(userName)
                + "&Password="
                + URLEncoder.encode(password);
        
        MyAsyncHttpClient client = new MyAsyncHttpClient();
        client.get(path, new MyHandler(){

            @Override
            public void onSuccess(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }

            @Override
            public void onFailure(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }
            
        });
    }    
    
    public void loginPost(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
        MyAsyncHttpClient client = new MyAsyncHttpClient();
        // 设置要提交的数据
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("UserName", userName));
        pairs.add(new BasicNameValuePair("Password", password));
        client.post(path, pairs, new MyHandler(){

            @Override
            public void onSuccess(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }

            @Override
            public void onFailure(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
            }
            
        });
    }  

}
View Code

 

二、使用GitHub上的异步Http开源框架

loopj/android-async-http

示例代码

package com.shz.login;

import java.net.URLEncoder;

import org.apache.http.Header;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.shz.asynchttp.R;

public class MainActivity extends Activity {

    private EditText txtUserName;
    private EditText txtPassword;
    private CheckBox cbRememberPwd;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txtUserName = (EditText)this.findViewById(R.id.txtUserName);
        this.txtPassword = (EditText)this.findViewById(R.id.txtPassword);
        this.cbRememberPwd = (CheckBox)this.findViewById(R.id.cbRememberPwd);
        
        
    }        
    
    public void loginGet(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login?UserName="
                + URLEncoder.encode(userName)
                + "&Password="
                + URLEncoder.encode(password);
        
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(path, new AsyncHttpResponseHandler() {
            
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
            }
            
            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
            }
        });
    }    
    
    public void loginPost(View view)
    {
        final String userName = this.txtUserName.getText().toString().trim();
        final String password = this.txtPassword.getText().toString().trim();
        
        if(TextUtils.isEmpty(userName) || TextUtils.isEmpty(password))
        {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        
        String path = "http://192.168.1.101/MyWebSite/AndroidTest/Home/Login";
        RequestParams params = new RequestParams();
        params.put("UserName", userName);
        params.put("Password", password);
        AsyncHttpClient client = new AsyncHttpClient();
        client.post(path, params, new AsyncHttpResponseHandler() {
            
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
            }
            
            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                Toast.makeText(MainActivity.this, statusCode+":"+new String(responseBody), 1).show();
            }
        });
    }  

}
View Code

 

posted @ 2014-08-20 23:29  萌浩  阅读(918)  评论(0编辑  收藏  举报