5.1提交数据到服务器

有两种方法,post跟get方法:post不需要带参,get可以直接在网址后带参请求。
post:

/**
     * 使用post的方式登录
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfPost(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");

            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000); // 连接的超时时间
            conn.setReadTimeout(5000); // 读数据的超时时间
            conn.setDoOutput(true); // 必须设置此方法, 允许输出
//          conn.setRequestProperty("Content-Length", 234);     // 设置请求头消息, 可以设置多个

            // post请求的参数
            String data = "username=" + userName + "&password=" + password;

            // 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();  
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();
            if(responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                Log.i(TAG, "访问失败: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

get:

/**
     * 使用get的方式登录
     * @param userName
     * @param password
     * @return 登录的状态
     */
    public static String loginOfGet(String userName, String password) {
        HttpURLConnection conn = null;
        try {
            //10.0.2.2手机上的pc平台服务器地址
            String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
            URL url = new URL("http://10.0.2.2:8080/Server/servlet/LoginServlet?" + data);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");       // get或者post必须得全大写
            conn.setConnectTimeout(10000); // 连接的超时时间
            conn.setReadTimeout(5000); // 读数据的超时时间

            int responseCode = conn.getResponseCode();
            if(responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                Log.i(TAG, "访问失败: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();      // 关闭连接
            }
        }
        return null;
    }

Main函数中的方法使用:

public void doGet(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();

        new Thread(
                new Runnable() {

                    @Override
                    public void run() {
                        // 使用get方式抓去数据
                        final String state = NetUtils.loginOfGet(userName, password);

                        // 执行任务在主线程中
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 就是在主线程中操作
                                Toast.makeText(MainActivity.this, state, 0).show();
                            }
                        });
                    }
                }).start();
    }

    public void doPost(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final String state = NetUtils.loginOfPost(userName, password);
                // 执行任务在主线程中
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 就是在主线程中操作
                        Toast.makeText(MainActivity.this, state, 0).show();
                    }
                });
            }
        }).start();
    }

根据流返回一个字符串信息:

/**
     * 根据流返回一个字符串信息
     * @param is
     * @return
     * @throws IOException 
     */
    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;

        while((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();

        String html = baos.toString();  // 把流中的数据转换成字符串, 采用的编码是: utf-8

//      String html = new String(baos.toByteArray(), "GBK");

        baos.close();
        return html;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值