0

Hi I have the following curl script

curl -i -X PUT -d "{\"loginList\":[{\"externalLoginKey\":\"1406560803453iGBoMm\",\"testStatus\":\"R\"}]}" -H "X-test-debug-override: true" -k  http://someapi/logins

I am trying to do a Http post using java. Following is my code. Am i doing something wrong? I am getting error but curl runs fine

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTesting {

public static void main(String[] args) throws Exception {

    String apiURL = "http://someapi/logins";
    URL url = new URL(apiURL);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    String str = "{\"loginList\":[{\"externalLoginKey\":\"1406565099034jZrHXe\",\"testStatus\":\"R\"}]}";
    con.disconnect();

    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("X-test-debug-override", "true");
    con.connect();

    OutputStream outStream = con.getOutputStream();
    DataOutputStream out = new DataOutputStream(outStream);
    out.writeBytes(str);
    out.flush();
    out.close();

    int responseCode = con.getResponseCode();
    System.out.println(responseCode);

}

}
3
  • 1
    What error are you getting? If you are getting an exception, please include the full stack trace in your question. Also, you probably should not call con.disconnect() on an HttpURLConnection you are about to use. Commented Jul 28, 2014 at 17:30
  • @VGR I am getting a 400 (Bad request) Commented Jul 28, 2014 at 17:32
  • did you put accept header in curl request? Commented Jul 28, 2014 at 17:54

1 Answer 1

3

From the curl man page:

-d, --data <data>

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.

(Emphasis mine.)

Even though you are sending JSON, your Content-Type needs to be "application/x-www-form-urlencoded". Which means you also need to encode your data using URLEncoder:

out.writeBytes(URLEncoder.encode(str, "UTF-8"));

By the way, your curl command uses the PUT method while your Java code uses the "POST" method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.