Android程序与服务器交互(一)

本文介绍了一种通过网络请求更新座位号的方法。该方法使用Java编程语言,涉及Android客户端发起异步任务,与服务器交互保存座位号的过程。具体步骤包括客户端发送HTTP POST请求到服务器,服务器接收并处理请求后返回结果。
摘要由CSDN通过智能技术生成

在公司一个项目中用到了这样一种网络请求方式,在此记录学习。

1.java代码

    /**
     * 访问网络改变座位号
     */
    private void saveSeatNumber() {
        Controller.getInstance(this).saveSeatNumber(
                getIntent().getStringExtra("prescriptionGroupNum"),
                seatNumberContent.getText().toString().trim(),
                new HandlerMessage() {
                    @Override
                    public void handlerMessage(String result) {

                        if (result.equals("1")) {

                        } else if (result.equals("2")) {
                            Toast.makeText(InfusionSeatNumberActivity.this,
                                    "保存失败", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(InfusionSeatNumberActivity.this,
                                    "未知错误", Toast.LENGTH_LONG).show();
                        }
                    }
                });

    }

2.Controller.java

public class Controller {
    private MySQLiteOpenHelper myOpenHelper;
    private AsyncTask task;
    private static Controller instance;
    private static Context context;

    public static Controller getInstance(Context c) {
        if (instance == null) {
            instance = new Controller();
        }
        context = c;
        return instance;
    }

    public void cancelTask(boolean cancel) {
        if (task != null) {
            task.cancel(cancel);
        }
    }
    /**
     * 保存座位号
     * 
     * @param prescriptionGroupNum
     * @param zw
     */
    public void saveSeatNumber(final String prescriptionGroupNum,
            final String zw, final HandlerMessage handlerMsg) {
        AsyncTask<Object, Integer, String> asyncTask = new AsyncTask<Object, Integer, String>() {
            ProgressDialog pd;

            @Override
            protected void onPreExecute() {
                pd = new ProgressDialog(context,
                        ProgressDialog.STYLE_HORIZONTAL);
                pd.setMessage(context.getString(R.string.pleasewait));
                pd.setCancelable(false);
                pd.show();
            }

            @Override
            protected String doInBackground(Object... objects) {
                return ServerDataUtil.getInstance().saveSeatNumber(
                        prescriptionGroupNum, zw);
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    handlerMsg.handlerMessage(result);
                }
                pd.dismiss();
            }
        };
        asyncTask.execute("");
    }
}

3.ServerDataUtil.java

public class ServerDataUtil {
    private final static int TIMEOUT = 30000;
    public final static String CONEXCEPTION = "网络异常,请重新操作";
    private HttpPost req;
    private HttpResponse rep;
    private static DefaultHttpClient client;
    private List<NameValuePair> params;
    private static ServerDataUtil fetcher;

    public static ServerDataUtil getInstance() {
        if (fetcher == null) {
            fetcher = new ServerDataUtil();
        }
        if (client == null) {
            BasicHttpParams params = new BasicHttpParams();
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            final SSLSocketFactory sslSocketFactory = SSLSocketFactory
                    .getSocketFactory();
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            ClientConnectionManager cm = new ThreadSafeClientConnManager(
                    params, schemeRegistry);
            client = new DefaultHttpClient(cm, params);
            final HttpParams param = client.getParams();
            HttpConnectionParams.setConnectionTimeout(param, TIMEOUT);
            HttpConnectionParams.setSoTimeout(param, TIMEOUT);
            ConnManagerParams.setTimeout(param, TIMEOUT);
        }
        return fetcher;
    }
    /**
     * 保存座位号
     * 
     * @return
     */
    public String saveSeatNumber(String prescriptionGroupNum, String zw) {
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("prescriptionGroupNum",
                prescriptionGroupNum));
        params.add(new BasicNameValuePair("zw", zw));
        try {
            req = new HttpPost(ClientStrings.getBASE_URL()
                    + ClientStrings.SAVE_SEAT_NUMBER);
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            req.setHeader(entity.getContentType());
            req.setEntity(entity);
            rep = client.execute(req);
            if (rep.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(rep.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Static.netexception;
    }

4.HandlerMessage.java

/**
 * 异步返回值
 * 
 * @author Administrator
 * 
 */
public interface HandlerMessage {
    public void handlerMessage(String result);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值