1

I am trying a POST API, which works with cURL command or POSTMan. However, sending the same call through HttpURLConnection doesn't work. Tried URL encoding the request params too. Still no luck. It's probably something wrong with the POST usage for HttpURLConnection.

    String url = "CORRECT_URL";
    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String urlParameters = "first_name=John&middle_name=Alfred&last_name=Smith&email=john.smith@gmail.com&phone=5555555555&zipcode=90401&dob=1970-01-22&ssn=543-43-4645&driver_license_number=F211165&driver_license_state=CA";
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", "Basic AUTH_TOKEN=");
    con.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    con.setRequestProperty( "charset", "utf-8");
    con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    con.setUseCaches( false );

    try {
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();
  }
  catch(Exception e) {
    System.out.println("Server returned error!");
    con.getResponseMessage();
  }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);
    System.out.println("Response : " + con.getResponseMessage());
Utkarsh Mishra
  • 480
  • 1
  • 7
  • 23
  • You `urlParameters` format is `GET` pass parameters... [use POST link](https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily) – Heng Lin Mar 11 '18 at 03:24
  • use @Boann method `Map` to pass parameters – Heng Lin Mar 11 '18 at 03:35
  • If you don't work, think about whether the parameters passed by the API itself are incorrect – Heng Lin Mar 11 '18 at 03:39

1 Answers1

0
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
...
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);

is overkill.

PrintWriter out = new PrintWriter(
   new OutputStreamWriter(con.getOutputStream(), "UTF-8")
);
out.print(urlParameters);

should do the job.

Moose Morals
  • 1,628
  • 25
  • 32