android之Http两种post请求方式

http请求分为GET和POST请求,POST请求中我们一般使用的是表单提交方式。这种是带参数名的提交方式,以HttpUrlConnection为例,示例代码如下:

/**
     * post请求
     * @param params    参数
     * @param url       地址
     * @return
     */
    public static String postMethodRequest(Map<String,String> params,String url){
        String response = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(TIME_OUT);
            if (null != params){
                Set<Map.Entry<String,String>> set = params.entrySet();
                if (null != set && !set.isEmpty()){
                    for (Map.Entry<String,String> entry : set){
                        connection.setRequestProperty(entry.getKey(),entry.getValue());
                    }
                }
            }
            connection.connect();
            int code = connection.getResponseCode();
            if (code == 200){
                response = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

还有一种是无参数的连接,实际就是利用输入输出流,提交信息请求并得到返回信息:

/**
     * post请求
     * @param params    参数
     * @param url       地址
     * @return
     */
    public static String postMethodRequest(String params,String url){
        String response = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(TIME_OUT);
            if (null != params){
                connection.getOutputStream().write(params.getBytes());
            }
            int code = connection.getResponseCode();
            if (code == 200){
                response = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


发布了23 篇原创文章 · 获赞 10 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/byxyrq/article/details/50498496
今日推荐