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();
                }
            }
        }
  • 相关阅读:
    c++多继承布局
    copy constructor
    default construction
    对象模型如何影响程序
    c++对象模型-对象模型
    在网站中引入特殊字体
    数组基础相关
    CSS3 transform3D
    即时效果--元素出现在页面特定区域时加载
    svg动态绘制饼状图
  • 原文地址:https://www.cnblogs.com/lizm166/p/15788512.html
Copyright © 2011-2022 走看看