Android_Http交互

1.HttpConnectApi.java
package TestNO01.httpconnect;

import java.util.ArrayList;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.util.Log;

public class HttpConnectApi {
    public static String SERVER_URL = "http://***.***.***.***:83/phone/servlet/LoginServlet";

    HttpClient httpclient;
    private static HttpConnectApi httpConnect;
    private String LOG = "day";
    public int maxTime = 15000;

    public HttpConnectApi() {
    }

    public static HttpConnectApi getInstance() {
        if (httpConnect == null) {
            httpConnect = new HttpConnectApi();
        }
        return httpConnect;
    }

    public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) {
        HttpResponse response = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, maxTime);
            HttpConnectionParams.setSoTimeout(httpParams, maxTime);
            // 新建HttpClient对象
            httpclient = new DefaultHttpClient(httpParams);
            response = httpclient.execute(httpRequest);
        } catch (Exception e) {
        }

        return response;
    }

    public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) {
        String query = URLEncodedUtils.format(stripNulls(nameValuePairs),
                HTTP.UTF_8);
        HttpGet httpGet = new HttpGet(url + "?" + query);
        return httpGet;
    }

    public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) {
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(
                    stripNulls(nameValuePairs)));
        } catch (Exception e) {
            // Log.d(LOG, "createHttpPost: "+e.toString());
        }
        return httpPost;
    }

    private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (int i = 0; i < nameValuePairs.length; i++) {
            NameValuePair param = nameValuePairs[i];
            if (param.getValue() != null) {
                params.add(param);
            }
        }
        return params;
    }

    public HttpResponse loginHttp(String account, String passwd) {
        HttpPost httpPost = null;
        try {
            String op = "login";
            HttpPost httppost = new HttpPost(SERVER_URL);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("op", op));
            nameValuePairs.add(new BasicNameValuePair("account", account));
            nameValuePairs.add(new BasicNameValuePair("passwd", passwd));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            return executeHttpRequest(httppost);
        } catch (Exception e) {
            Log.d(LOG, "test post: " + e.toString());
        }
        return null;
    }

}



2.定义成员变量:
public Task task;    //后台执行任务
private HttpConnectApi httpConnect;    //网络交互
private String value;    //网络交互成功后的内容



3.前台事件处理
// 前台事件处理
private final Handler handler = new Handler(Looper.getMainLooper()) {
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        switch (msg.what) {
        case RESULT_LOGIN_FAIL:    //登陆失败
            myDialog.hide();

            String str = "用户名密码错误";
            // 登录失败
            new AlertDialog.Builder(Login.this).setTitle("登录失败!")
                    .setMessage(str).setPositiveButton("确定", null).show();
            break;

        case RESULT_LOGIN_SUCCESS:    //登陆成功
            myDialog.hide();
            // 显示接到的数据
            new AlertDialog.Builder(Login.this).setTitle("登录成功!")
                    .setMessage(value).setPositiveButton("确定", null).show();
            break;

        case RESULT_SCROLLBAR_OPEN:    //由onPreExecute()调用打开滚动框
            String sTitle = "提示";
            String sMsg = "正在请求数据...";
            myDialog = ProgressDialog.show(Login.this, sTitle, sMsg, true);
            break;

        }
    }

};


4.Task类,用于在后台处理数据。
// AsyncTask<>的参数类型由用户设定,这里设为三个String
// 第一个String代表输入到任务的参数类型,也即是doInBackground()的参数类型
// 第二个String代表处理过程中的参数类型,也就是doInBackground()执行过程中的产出参数类型,通过
// publishProgress()发消息
// 传递给onProgressUpdate()一般用来更新界面
// 第三个String代表任务结束的产出类型,也就是doInBackground()的返回值类型,和onPostExecute()的参数类型
private class Task extends AsyncTask<String, String, String> {

    // 后台执行的耗时任务,接收参数并返回结果
    // 当onPostExecute()执行完,在后台线程中被系统调用
    @Override
    protected String doInBackground(String... params) {
        if (params[0].equals(TASK_LOGIN)) {
            return funLogin();
        }
        return "";
    }

    // 任务执行结束后,在UI线程中被系统调用
    // 一般用来显示任务已经执行结束
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result.equals("login_fail")) {
            Message msg = Message.obtain();
            msg.what = RESULT_LOGIN_FAIL;
            handler.sendMessage(msg);
        } else if (result.equals("login_success")) {
            Message msg = Message.obtain();
            msg.what = RESULT_LOGIN_SUCCESS;
            handler.sendMessage(msg);
        }
    }

    // 最先执行,在UI线程中被系统调用
    // 一般用来在UI中产生一个进度条
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Message msg = Message.obtain();
        msg.what = RESULT_SCROLLBAR_OPEN;
        handler.sendMessage(msg);
    }

    // 更新界面操作,在收到更新消息后,在UI线程中被系统调用
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }

}



5.Task函数中用到的登陆函数。
public String funLogin() {
    String result = "login_fail";
    httpConnect = HttpConnectApi.getInstance();

    try {
        String account = mAccount.getText().toString();
        String passwd = mPasswd.getText().toString();

        HttpResponse response = httpConnect.loginHttp(account, passwd);
        if (response.getStatusLine().getStatusCode() == 200) {
            result = "login_success";
            value = EntityUtils.toString(response.getEntity());

        }
    } catch (Exception e) {
    }
    return result;
}

你可能感兴趣的:(exception,android,String,null,任务,login)