I have used below sample code in my project for Sending request and collecting response from an https URL:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Sample {
public static void main(String[] args) {
HttpURLConnection con = null;
Map<String, String> parameters = getParameters();
String urlParameters = getDataString(parameters);
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
try {
URL myurl = new URL("https://samplewebsite/oauth2/token");
con = (HttpURLConnection) myurl.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
StringBuilder content;
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
content = new StringBuilder();
while ((line = br.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
System.out.println(content.toString());
}catch(Exception e){
System.out.println(e);
}
finally {
if(con!=null)
con.disconnect();
}
}
private static String getDataString(Map<String, String> params) {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return result.toString();
}
public static Map<String, String> getParameters() {
Map<String, String> parameters = new HashMap<>();
parameters.put("client_id", "id");
parameters.put("client_secret", "secret");
parameters.put("grant_type", "client_credentials");
parameters.put("scope", "list of scopes");
return parameters;
}
}
While debugging code I am getting PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target error at this line DataOutputStream wr = new DataOutputStream(con.getOutputStream());
Strange part is when I run shared sample code in same environment it works fine but with entire project it throw that error. Can anyone point me to the exact issue?
It looks like you are trying to connect to a http resource over ssl and certificate of host server is self-signed or something like that. So you need to add this certificate in your local trusted keystore of JVM with keytool command. Also you may check out this article for more detailed instructions - https://confluence.atlassian.com/kb/unable-to-connect-to-ssl-services-due-to-pkix-path-building-failed-error-779355358.html.