Android Post方式提交数据

来源:互联网 发布:最新博客网站程序源码 编辑:程序博客网 时间:2024/06/05 01:04

1.场景

Android中经常会用到使用post方式请求json格式的数据。请求参数也是json格式的数据,在这里封装一下,方便日后查找。

2.HttpUrlConnection实现post请求

/**     * 提交请求     *     * @param strUrlPath 请求的url     * @param params     请求参数     * @param encode     请求参数的编码方式     * @return     */    public static String submitPostData(String strUrlPath, Map<String, Object> params, String encode) {        int response = -1;        byte[] data = new JSONObject(params).toString().getBytes();        try {            URL url = new URL(strUrlPath);            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间            httpURLConnection.setDoInput(true);            //打开输入流,以便从服务器获取数据            httpURLConnection.setDoOutput(true);           //打开输出流,以便向服务器提交数据            httpURLConnection.setRequestMethod("POST");     //设置以Post方式提交数据            httpURLConnection.setUseCaches(false);          //使用Post方式不能使用缓存            //设置请求体的类型是文本类型            httpURLConnection.setRequestProperty("Content-Type", "application/json");            httpURLConnection.setRequestProperty("Char-Set", encode);            //设置请求体的长度            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));            //获得输出流,向服务器写入数据            OutputStream outputStream = httpURLConnection.getOutputStream();            outputStream.write(data);            //获得服务器的响应码            response = httpURLConnection.getResponseCode();            if (response == HttpURLConnection.HTTP_OK) {                //处理服务器的响应结果                InputStream inputStream = httpURLConnection.getInputStream();                String result = dealResponseResult(inputStream);                if (!TextUtils.isEmpty(result)) {                    try {                        JSONObject jsonObject = new JSONObject(result);                        boolean flag = jsonObject.optBoolean("success", false);                        if (flag) {                            response = 200;                        } else {                            response = -1;                        }                    } catch (JSONException e) {                        e.printStackTrace();                    }                } else {                    response = -1;                }            }        } catch (IOException e) {            Log.e(TAG, String.format("err: %s", e.toString()));        }        return response + "";    }    /**     * 处理服务器的响应结果(将输入流转化成字符串)     *     * @param inputStream 服务器的响应输入流     * @return     */    public static String dealResponseResult(InputStream inputStream) {        String resultData;      //存储处理结果        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        byte[] data = new byte[1024];        int len = 0;        try {            while ((len = inputStream.read(data)) != -1) {                byteArrayOutputStream.write(data, 0, len);            }        } catch (IOException e) {            e.printStackTrace();        }        resultData = new String(byteArrayOutputStream.toByteArray());        return resultData;    }


原创粉丝点击