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();
            }
        }
    }

 

posted @ 2022-01-11 15:23  整合侠  阅读(6341)  评论(0编辑  收藏  举报