Skip to content

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target #333

@ghost

Description

I am not fan of Spring RestTemplate yet, but I would like to use the HttpClient API. My following code works fine, but when tried to convert it to HttpClient, it's giving errors

public static void main(String[] args) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        //headers.add("Content-Type", "application/x-www-form-urlencoded");
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString());
        headers.add("Authorization", "Basic XXXXXXXXXXXXX");

        String url = "https://XXXXXXXXX:8243/token";

        String data = "grant_type=password&username=XXXX&password=XXXX";

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<String>(data,headers);
        System.out.println("ENTITY : "+entity);
        HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        System.out.println("RESPONSE : "+response.getBody());
    }

But if tried same with HttpClient causing problem. I think data is not getting set properly that's why it's causing proble. DO you know how we can pass data in HttpClient?

public static void main(String[] args) throws ClientProtocolException, IOException {
        String url = "https://XXXXXXXXXX:8243/token";
        String data = "grant_type=password&username=admin&password=admin";

        HttpClient client = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Authorization", "Basic XXXXXXXXXXXX");

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(3);
        urlParameters.add(new BasicNameValuePair("grant_type", "password"));
        urlParameters.add(new BasicNameValuePair("username", "XXXX"));
        urlParameters.add(new BasicNameValuePair("password", "XXXX"));
        HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);

        httpPost.setEntity(new StringEntity(data));

        HttpResponse httpResponse = client.execute(httpPost);
        System.out.println(httpResponse);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions