为了账号安全,请及时绑定邮箱和手机立即绑定

POST请求发送json数据java HttpUrlConnection

POST请求发送json数据java HttpUrlConnection

慕娘9325324 2019-09-20 14:45:41
我开发了一个java代码,使用URL和HttpUrlConnection将以下cURL转换为java代码。卷曲是:curl -i 'http://url.com' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": { "passwordCredentials": {"username": "adm", "password": "pwd"},"tenantName":"adm"}}'我编写了这段代码,但它始终给出了HTTP代码400错误的请求。我找不到遗漏的东西。String url="http://url.com";URL object=new URL(url);HttpURLConnection con = (HttpURLConnection) object.openConnection();con.setDoOutput(true);con.setDoInput(true);con.setRequestProperty("Content-Type", "application/json");con.setRequestProperty("Accept", "application/json");con.setRequestMethod("POST");JSONObject cred   = new JSONObject();JSONObject auth   = new JSONObject();JSONObject parent = new JSONObject();cred.put("username","adm");cred.put("password", "pwd");auth.put("tenantName", "adm");auth.put("passwordCredentials", cred.toString());parent.put("auth", auth.toString());OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());wr.write(parent.toString());wr.flush();//display what returns the POST requestStringBuilder sb = new StringBuilder();  int HttpResult = con.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) {    BufferedReader br = new BufferedReader(            new InputStreamReader(con.getInputStream(), "utf-8"));    String line = null;      while ((line = br.readLine()) != null) {          sb.append(line + "\n");      }    br.close();    System.out.println("" + sb.toString());  } else {    System.out.println(con.getResponseMessage());  }  
查看完整描述

3 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

您的JSON不正确。代替


JSONObject cred = new JSONObject();

JSONObject auth=new JSONObject();

JSONObject parent=new JSONObject();

cred.put("username","adm");

cred.put("password", "pwd");

auth.put("tenantName", "adm");

auth.put("passwordCredentials", cred.toString()); // <-- toString()

parent.put("auth", auth.toString());              // <-- toString()


OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());

wr.write(parent.toString());


JSONObject cred = new JSONObject();

JSONObject auth=new JSONObject();

JSONObject parent=new JSONObject();

cred.put("username","adm");

cred.put("password", "pwd");

auth.put("tenantName", "adm");

auth.put("passwordCredentials", cred);

parent.put("auth", auth);


OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());

wr.write(parent.toString());

因此,应该只为外部对象调用一次JSONObject.toString()。


另一件事(很可能不是你的问题,但我想提一下):


为了确保不会遇到编码问题,您应该指定编码,如果不是UTF-8:


con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

con.setRequestProperty("Accept", "application/json");


// ...


OutputStream os = con.getOutputStream();

os.write(parent.toString().getBytes("UTF-8"));

os.close();


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 3180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信