码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-03-19 22:48:29      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

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 "请求失败";
    }

 

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

标签:

原文地址:http://www.cnblogs.com/taoshihan/p/5296562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!