POST请求发送json数据java HttpUrlConnection

我已经开发了一个java代码,使用URL和HttpUrlConnection将下面的cURL转换为java代码。 curl是:

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不好的请求。 我找不到缺less的东西。

 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 request StringBuilder 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()); } 

你的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"); // ... OutputStream os = con.getOutputStream(); os.write(parent.toString().getBytes("UTF-8")); os.close(); 
 private JSONObject uploadToServer() throws IOException, JSONException { String query = "https://example.com"; String json = "{\"key\":1}"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(json.getBytes("UTF-8")); os.close(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8"); JSONObject jsonObject = new JSONObject(result); in.close(); conn.disconnect(); return jsonObject; } 

你可以使用这个代码来连接和请求使用http和json

 try { URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet" + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo" + "&access_token=" + access_token); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

如果你看到一个错误添加这个,但这不是一个好的工作。

 if (Build.VERSION.SDK_INT >= 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 

正确的答案是好的, 但是

 OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream()); wr.write(parent.toString()); 

不为我工作 ,而不是它, 使用

 byte[] outputBytes = rootJsonObject.getBytes("UTF-8"); OutputStream os = httpcon.getOutputStream(); os.write(outputBytes); 

我有一个类似的问题,我得到400,只有PUT的错误请求,在POST请求是完全正常的。

下面的代码工作正常POST,但是给BAD请求PUT:

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

在做出以下更改后,POST和PUT都可以正常工作

 conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); os.write(json.getBytes("UTF-8"));