POST request send JSON data Java HttpUrlConnection POST request send JSON data Java HttpUrlConnection java java

POST request send JSON data Java HttpUrlConnection


Your JSON is not correct. Instead of

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());

write

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());

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not 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();


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;    }


You can use this code for connect and request using http and json

try {                 URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"                + "&key="+key                + "&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();      }