如何通过URL和HttpURLConnection类在Request body中添加对象

问题描述 投票:1回答:2

我指的是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'作为对象?任何帮助将不胜感激!

java url post httpurlconnection
2个回答
1
投票

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

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

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

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

这就是全部,你的代码将正常工作。


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");
© www.soinside.com 2019 - 2024. All rights reserved.