POST request send JSON data Java HttpUrlConnection

JavaJsonPostCurlHttpurlconnection

Java Problem Overview


I have developed a Java code that convert the following cURL to java code using URL and HttpUrlConnection. the cURL is :

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"}}'

I have written this code but it always gives HTTP code 400 bad request. I couldn't find what is missing.

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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

the correct answer is good , but

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

not work for me , instead of it , use :

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

Solution 5 - Java

I had a similar issue, I was getting 400, Bad Request only with the PUT, where as POST request was perfectly fine.

Below code worked fine for POST but was giving BAD Request for PUT:

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

After making below changes worked fine for both POST and PUT

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

Solution 6 - Java

Here is full Code and Solutions

PostJSONWithHttpURLConnection.java Class

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostJSONWithHttpURLConnection {
    String charset = "UTF-8";
    HttpURLConnection con;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder result;

    public JSONObject makeHttpRequest(String url,
                                      String paramsJSON) {
        try {
            urlObj = new URL(url);
            con = (HttpURLConnection) urlObj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");

            con.setDoOutput(true);
            con.setReadTimeout(60000);
            con.setConnectTimeout(60000);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = paramsJSON.getBytes(charset);
                os.write(input, 0, input.length);
            }

            int code = con.getResponseCode();
            Log.d("HTTP CODE", String.valueOf(code));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(con.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        con.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }
}

Use of Code on doInBackground(String... strArr)

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
String writeValueAsString = objectMapper.writeValueAsString(jSONObject);   
PostJSONWithHttpURLConnection jsonPOST = new PostJSONWithHttpURLConnection();
JSONObject json = jsonPOST.makeHttpRequest(SERVER_ADDRESS + "YOUR_API", writeValueAsString);

jSONObject is a Json Like:

{
"Password":"PASSWORD",
"FullName":"Full Name",
"Username":"USER_NAME"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3244172View Question on Stackoverflow
Solution 1 - JavahgoeblView Answer on Stackoverflow
Solution 2 - JavaNickUnuchekView Answer on Stackoverflow
Solution 3 - JavaBurak DurmuşView Answer on Stackoverflow
Solution 4 - JavaAdnan Abdollah ZakiView Answer on Stackoverflow
Solution 5 - Javavkumar22View Answer on Stackoverflow
Solution 6 - JavaMonzurView Answer on Stackoverflow