如何通过URL和HttpURLConnection类在请求正文中添加对象

时间:2018-09-18 06:53:59

标签: java url post httpurlconnection

我指的是this问题,我有以下代码段:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

但是我想在请求正文中添加属性数组,因此我的请求数据如下所示:

{
  "accountEnabled": true,
  "city": "Delhi",
  "country": "India",
  "department": "Human Resources",
  "displayName": "Adam G",
  "passwordProfile": {
    "password": "Test1234",
    "forceChangePasswordNextSignIn": false
  },
  "officeLocation": "131/1105",
  "postalCode": "98052",
  "preferredLanguage": "en-US",
  "state": "MH",
 }

当我将“ passwordProfile ”作为对象时,如何在此处发送数组? 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

首先要发送问题中提到的json对象,您需要按如下所示更改内容类型

conn.setRequestProperty("Content-Type","application/json");

然后使用Jackson 2库,您可以从任何对象获取json字符串值,这些对象将成为我们的发布数据。例如:

ObjectMapper mapper = new ObjectMapper();
byte[] postData       = mapper.writeValueAsString(staff).getBytes( StandardCharsets.UTF_8 );

仅此而已,您的代码即可正常工作。

答案 1 :(得分:0)

要将“项目”发送到请求正文中,您可以执行以下操作:

声明:

String json = "{\"accountEnabled\": true, \"city\": \"Delhi\",..................";

然后

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
OutputStream os = con.getOutputStream();
os.write(json.getBytes());

在这种情况下,您正在发送一个json,所以重要的是:

con.setRequestProperty("Content-Type", "application/json");