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