java如何实现http之post请求将参数放入到body中并发送呢?
下文笔者讲述post请求时--参数放入Body中的方法及示例分享,如下所示
body放入post请求
实现思路: 1.打印urlConnection连接 2.生成一个new OutputStreamWriter(connection.getOutputStream(),"UTF-8")对象 3.向对象中写入params 采用以上方法,即可向指定url的body中请求参数例: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(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。