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

@Test
public void testByTenantId() throws Exception {
    String tenantId="nhs7wd2c";

    String defURL = "http://bd.basdoc.com/rest/data/transfer";
    URL url = new URL(defURL);
    // 打开和URL之间的连接
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setRequestMethod("POST");//请求post方式
    con.setUseCaches(false); // Post请求不能使用缓存
    con.setDoInput(true);// 设置是否从HttpURLConnection输入,默认值为 true
    con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 false
    
    //设置header内的参数 connection.setRequestProperty("健, "值");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("isTree", "true");
    con.setRequestProperty("isLastPage", "true");

    //设置body内的参数,put到JSONObject中
    JSONObject param = new JSONObject();
    param.put("sysId", "diwork");
    param.put("tenantId", tenantId);

    // 建立实际的连接
    con.connect();

    // 得到请求的输出流对象
    OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
    writer.write(param.toString());
    writer.flush();

    // 获取服务端响应,通过输入流来读取URL的响应
    InputStream is = con.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    StringBuffer sbf = new StringBuffer();
    String strRead = null;
    while ((strRead = reader.readLine()) != null) {
        sbf.append(strRead);
        sbf.append("\r\n");
    }
    reader.close();

    // 关闭连接
    con.disconnect();

    // 打印读到的响应结果
    System.out.println("运行结束:"+sbf.toString());

}

你可能感兴趣的:(Java基础)