HttpURLConnection的post请求传递header参数和body参数的具体方法实现

时间:2025-04-22 18:51:36
@Test public void testByTenantId() throws Exception { String tenantId="nhs7wd2c"; String defURL = "/rest/data/transfer"; URL url = new URL(defURL); // 打开和URL之间的连接 HttpURLConnection con = (HttpURLConnection)(); ("POST");//请求post方式   (false); // Post请求不能使用缓存 (true);// 设置是否从HttpURLConnection输入,默认值为 true (true);// 设置是否使用HttpURLConnection进行输出,默认值为 false   //设置header内的参数 ("健, "值"); ("Content-Type", "application/json"); ("isTree", "true");   ("isLastPage", "true"); //设置body内的参数,put到JSONObject中 JSONObject param = new JSONObject(); ("sysId", "diwork"); ("tenantId", tenantId); // 建立实际的连接 (); // 得到请求的输出流对象 OutputStreamWriter writer = new OutputStreamWriter((),"UTF-8"); (()); (); // 获取服务端响应,通过输入流来读取URL的响应 InputStream is = (); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String strRead = null; while ((strRead = ()) != null) { (strRead); ("\r\n"); } (); // 关闭连接 (); // 打印读到的响应结果 ("运行结束:"+()); }