Android网络编程之使用post方式提交数据

来源:互联网 发布:零用钱软件赚钱靠谱吗 编辑:程序博客网 时间:2024/05/16 19:42

上篇写了使用get方式提交数据,post和get两种方式的不同点就是,get是把要提交的数据截取成字符串添加到地址后面的。而post方式是通过流提交给服务器的。另外get只用提交表单数据即可,post还要提交另外的几项数据。

  • 使用post表单提交数据,http请求头会有这样两行数据
Content-Type:application/x-www-form-urlencodedContent-Length:36

浏览器向服务端发送数据的时候会自动添加这些请求头,但是安卓客户端不会,所以需要我们手动添加这些。

    public void click(View v){        EditText et_name = (EditText) findViewById(R.id.et_name);        EditText et_password = (EditText) findViewById(R.id .et_password);        final String name = et_name.getText().toString();        final String pass = et_password.getText().toString();        Thread t = new Thread(){            @Override            public void run() {                //提交的数据需要进行URL编码,字母和数字编码后都不变                String path = "http://192.168.252.1:8080/web/LoginServlet";                try {                    URL url = new URL(path);                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    conn.setRequestMethod("POST");                    conn.setReadTimeout(5000);                    conn.setConnectTimeout(5000);                    //拼接处要提交的字符串                    @SuppressWarnings("deprecation")                    String data = "name="+URLEncoder.encode(name)+"&password="+pass;                    //为post添加两行属性                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                    conn.setRequestProperty("Content-Length", data.length()+"");                    //因为post是通过流往服务器提交数据的,所以我们需要设置一个输出流                    //设置打开输出流                    conn.setDoOutput(true);                    //拿到输出流                    OutputStream os = conn.getOutputStream();                    //使用输出流向服务器提交数据                    os.write(data.getBytes());                    if(conn.getResponseCode() == 200){                        InputStream is = conn.getInputStream();                        String text = utils.getTextFromStream(is);                        //消息队列机制,把读取出来的数据交给handler发送给主线程刷新UI                        Message msg = handler.obtainMessage();                        msg.obj = text;                        handler.sendMessage(msg);                    }                                   } catch (Exception e) {                    e.printStackTrace();                }                           }        };        t.start();    }

其他地方的代码只需要把GET都修改成POST即可

0 0