GET/POST提交数据到服务器案例

采用get方式提交数据到服务器

在web项目中的LoginServlet.java文件:

public class LoginServlet extends HttpServlet{

   

    private static final long serialVersionUID = 1L;

   

    public LoginServlet(){

        super();

    }

 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String sername = request.getParameter('username');//默认编码 iso-8859-1

        String password = request.getParameter("password");

        System.out.println("username:"+new String(username.getBytes("iso-8859-1"),"utf-8"));//避免中卫乱码

        System.out.println("password:"+password);

        if("feiniu".equals(username)&&"123".equals(password)){

            response.getOutputStream().write("Success".getBytes());

        }else{

            response.getOutputStream().write("Error".getBytes());

        }

    }

}

 

接下来开始做xml布局文件:

    <EditText

        android:id="@+id/et_password"

        android:layout_width="match_parent"

        android:hint="请输入用户名"

        layout_height="wrap_content"/>

    <EditText

        android:id="@+id/et_username"

        android:hint="请输入密码"

        android:layout_width="match_parent"

        android:inputType="textPassword"

        layout_height="wrap_content"/>

    <Button

        android:id="@+id/button"

        android:onClick="click"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Login"/>

 

Activity源文件:

    public void click(View view){

        final String username = et_username.getText().toString().trim();

        final String password = et_password.getText().toString().trim();

 

        new Thread(){

            public void run(){

                final String result = LoginService.loginByGet(username,password);

                if(result != null){

                    runOnUiThread(new Runnable(){   //可直接移交给主线程操作

                        public void run(){

                            Toast.makeText(MainActivity.this, result, 0).show();

                        }

                    });

                }else{

                    //请求失败

                    runOnUiThread(new Runnable(){   //可直接移交给主线程操作

                        public void run(){

                            Toast.makeText(MainActivity.this, "请求失败...", 0).show();

                        }

                    });

                }

            };

        }.start();

       

 

    }

 

为方便多种请求数据,定义一个类:

public class LoginService{

    public static String loginByGet(String username, String password){

        //提交数据到服务器

        //拼路径

        try{

            String path = "http://192.168.1.110:8080/web/LoginServlet?username="

            + URLEncoder.encode(username,"UTF-8")

            +"&password="+ URLEncoder.encode(password,"UTF-8");

            URL url = new URL(path);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setConnectTimeout(5000);

            conn.setRequestMethod("GET");

 

            int code = conn.getResponseCode();

            if(code == 200){

                //请求成功

                InputStream is = conn.getInputStream();

                String text = StreamTools.readInputStream(is);

                return text;

            }else{

                return null;

            }

        }catch(Exception e){

            e.printStackTrace();

        }

        return null;

    }

}

 

StreamTools.java源文件:

public class  StreamTools{

    //把输入流的内容转化成字符串

    public static String readInputStream(InputStream is){

        try{

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int len = 0;

            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1){

                baos.write(buffer, 0, len);

            }

            is.close();

            baos.close()

            byte[] result = baos.toByteArray();

            //试着解析 result 里面的字符串

            String temp = new String(result);

            return temp;

        }catch(Exception e){

            e.printStackTrace();

            return "获取失败";

        }

    }

}

 

 

GET/POST:

GET:    组拼url的方式提交数据到服务器    url 最大长度  最长不超过4K(不超过1K主要是针对IE浏览器来说)

POST:   直接浏览器把数据写个服务器   流的方式。

 

POST的请求:

首先在LoginServlet.java文件里添加doPost方法:

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)

                throws ServletException, IOException {

            doGet(req, resp);

    }

 

在JSP文件中添加两个表单,对比一下get/post:

<form action="LoginServlet" method="post">

    用户名:<input name="username" type="text"><br>

    密   码:<input name="password" type="password"><br>

    <input name="submit" type="submit">

</form>

<br>

<form action="LoginServlet" method="post">

    用户名:<input name="username" type="text"><br>

    密   码:<input name="password" type="password"><br>

    <input name="submit" type="submit">

</form>

 

在web中运行项目可以看到:post比get多出了类型、长度、请求的数据。

 

接下来返回客户端,在LoginService文件中添加一下方法:

public static String loginByPOST(String username, String password){

        //提交数据到服务器

        //拼路径

        try{

            String path = "http://192.168.1.110:8080/web/LoginServlet";

            URL url = new URL(path);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setConnectTimeout(5000);

            conn.setRequestMethod("POST");

 

            //准备数据

            String data = "username=" + URLEncoder.encode(username,"UTF-8")

             + "&password=" + URLEncoder.encode(password,"UTF-8"); //解决中文请求乱码问题

            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());

 

            int code = conn.getResponseCode();

            if(code == 200){

                //请求成功

                InputStream is = conn.getInputStream();

                String text = StreamTools.readInputStream(is);

                return text;

            }else{

                return null;

            }

        }catch(Exception e){

            e.printStackTrace();

        }

        return null;

    }

 

在界面添加一个按钮,用法与上面的get操作一样,在此就不在累赘.

posted @ 2015-10-25 16:41  飞牛冲天  阅读(246)  评论(0编辑  收藏  举报