Search code examples
javaapache-httpclient-4.xapache-commons-httpclient

How do i set basic authentication using apache httpClient


I am trying to do a PATCH request using Apache httpclient and I am unsure how to set basic authentication. This is how im currently trying to do it. I know that my auth params are correct and i can authenticate using GET ... but for GET im currently using httpURLConnection rather than Apache httpClient .

With this code I am getting back a 403 response and I believe its because im not setting the auth info correctly. I know that i just need to do basic authentication and feed it X_AUTH_USER, X_AUTH_CRED.

Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(X_AUTH_USER, X_AUTH_CRED.toCharArray());
        }
    });

    HttpClient client = HttpClientBuilder.create().build();
    HttpPatch patch = new HttpPatch(buildUrl());


    try {
        StringEntity input = new StringEntity(buildJson(jsonList));
        input.setContentType("application/json");
        patch.setEntity(input);

        System.out.println(patch);

        HttpResponse response = client.execute(patch);

        System.out.print(response.getStatusLine());
        for(Header header : response.getAllHeaders()){
            System.out.println(header.getName() + " : " + header.getValue());
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution

  • Update:

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("UserName", "P@sw0rd".toCharArray());
        }
    });
    

    You also need to set other header properties: (example)

    response.addHeader("Access-Control-Allow-Methods", "");
    response.setHeader("Access-Control-Allow-Origin", "http://podcastpedia.org");
    //allows CORS requests only coming from podcastpedia.org
    

    Code to add a basic authentication property to an httpURLConnection

    String basic = "Basic " + Base64.encodeToString(("admin:1234").getBytes(), Base64.NO_WRAP);
    
    con.setRequestProperty("Authorization", basic);