zoukankan      html  css  js  c++  java
  • Java:调用http的post方式带body参数

    调用http的post方式带body参数

    
    
    import java.net.HttpURLConnection;
    import java.net.URL;
    //方法,参数params,{"image":"str_base"}
    public static String httpPost(String serverURL, String params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            InputStream is = null;
            OutputStreamWriter writer = null;
            try{
                StringBuffer sbf = new StringBuffer();
                String strRead = null;
                URL url = new URL(serverURL);
                connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("POST");//请求post方式
                connection.setDoInput(true);
                connection.setDoOutput(true);
                //header内的的参数在这里set
                //connection.setRequestProperty("key", "value");
                connection.setRequestProperty("Content-Type", "application/json;charset=\"UTF-8\"");
                connection.connect();
                writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
                //body参数放这里
                writer.write(params);
                writer.flush();
                is = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                is.close();
                writer.close();
                connection.disconnect();
                String results = sbf.toString();
                System.out.println("str_base>>>:"+results);
                return results;
            }catch (IOException e){
                e.printStackTrace();
                return "";
            }finally {
                try {
                    if(connection != null){
                        connection.disconnect();
                    }
                    if(reader != null){
                        reader.close();
                    }
                    if(is != null){
                        is.close();
                    }
                    if(writer != null){
                        writer.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
  • 相关阅读:
    kafka cdh 安装
    【转】Public key for *.rpm is not installed,使用yum安装时报错
    12.yaml的简单使用
    python基础教程第三版阅读笔记(一)
    Python库文件安装失败问题及解决方式汇总-持续更新ing~
    taiko初体验
    VMware之USB设备连接
    C++之DLL的动态加载与静态加载初尝试
    C++课堂练习二
    C++课堂练习三
  • 原文地址:https://www.cnblogs.com/lizm166/p/15788512.html
Copyright © 2011-2022 走看看