安卓发送Get、Post请求,解决参数乱码问题

53 篇文章 0 订阅
/**
     * 发送GET请求
     * @param urlAddress 请求的网址
     * @param requestParams 请求参数
     * @return
     */
    protected String submitGetRequest(String urlAddress, RequestParams requestParams) {
        String result = null;
        HttpURLConnection connection = null;
        URL url = null;

        try {
            if (requestParams != null) {
                // 请求参数
                Map<String, String> params = requestParams.getParams();
                int paramSize = params.size();
                int index = 1;
                StringBuilder paramsBuilder = new StringBuilder();
                paramsBuilder.append("?");
                for (String key : params.keySet()) {
                    paramsBuilder.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8"));
                    if (index < paramSize) {
                        paramsBuilder.append("&");
                        index++;
                    }
                }
                url = new URL(urlAddress + paramsBuilder.toString());
            } else {
                url = new URL(urlAddress);
            }

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-type", "text/html");
            // 不要用cache,用了也没有什么用,因为我们不会经常对一个链接频繁访问。(针对程序)
            connection.setUseCaches(false);
            connection.setConnectTimeout(6 * 1000);
            connection.setReadTimeout(6 * 1000);
            connection.setRequestProperty("Charset", "utf-8");

            connection.connect();

            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                InputStream inputStream  = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line).append("\n");
                }
                result = builder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     * @return
     */
    protected String submitPostRequest(String urlAddress, RequestParams requestParams) {
        String result = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlAddress);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");

            //connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows 7)");
            connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
            connection.setRequestProperty("Accept-Language", "zh-cn");
            //connection.setRequestProperty("UA-CPU", "x86");
            //connection.setRequestProperty("Accept-Encoding", "gzip");
            // 很重要
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setConnectTimeout(6 * 1000);
            connection.setReadTimeout(6 * 1000);
            // 发送POST请求必须设置这两项
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Charset", "utf-8");

            connection.connect();

            if (requestParams != null) {
                // 请求参数
                Map<String, String> params = requestParams.getParams();
                int paramSize = params.size();
                int index = 1;
                StringBuilder paramsBuilder = new StringBuilder();
                for (String key : params.keySet()) {
                    paramsBuilder.append(key).append("=").append(params.get(key));
                    if (index < paramSize) {
                        paramsBuilder.append("&");
                        index++;
                    }
                }

                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(paramsBuilder.toString());
                writer.flush();
                writer.close();
            }

            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                InputStream inputStream = null;
                inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line).append("\n");
                }
                result = builder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ithouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值