user3246489
user3246489

Reputation: 1141

Trying to use Java Http URL connection to do curl command

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

}

}

Upvotes: 0

Views: 2080

Answers (1)

VGR
VGR

Reputation: 44414

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.

Upvotes: 3

Related Questions