[android] 采用post的方式提交数据

GET:内部实现是组拼Url的方式,http协议规定最大长度4kbie浏览器限制1kb

POSTGET的区别比较了一下,多了几条信息

Content-Type:application/x-www-form-urlencoded

Content-Length:93

主体内容

 

只需修改上一节代码中的几个地方:

调用HttpURLConnection对象的setRequestMethod(“POST”)方法

调用HttpURLConnection对象的setRequestProperty()方法,把上面的几条头信息加进去

拼接好内容比如 String data=”username=”+username,调用String对象的length()方法,返回长度,长度+””空字符串转成String类型

调用HttpURLConnection对象的setDoOutput(true)方法,是否允许写数据

调用HttpURLConnection对象的getOutputStream()方法,获取OutputStream对象

调用OutputStream对象的write(buffer)方法,向服务器写数据,参数:bufferbyte[]数组,调用String对象的getBytes()方法,得到byte[]

service:

 

    /**
     * POST传递参数
     * 
     * @param username
     * @param password
     * @return
     */
    public static String loginByPost(String username, String password) {
        String path = ROOT_PATH;
        try {
            URL url = new URL(path);
            
            String data="username="+username+"&password="+password;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //设置头信息
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", data.length()+"");
            //写数据
            conn.setDoOutput(true);
            OutputStream os=conn.getOutputStream();
            os.write(data.getBytes());
            
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                String info = StreamTools.readInputStream(is);
                return info;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "请求失败";
    }

 

posted @ 2016-03-19 22:17  唯一客服系统开发笔记  阅读(344)  评论(0编辑  收藏  举报