Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Authentication for JAVA Application using OkHttp

Tags:

java

okhttp

First I wanted to authenticate my java application using OkHttp and then after authentication the response returns a session ID(key) that I wanted to use in subsequent API calls. below is the code that I am using to achieve this.

    String url = "my application url";
    String username = "xxx";  
    String password = "zzz";  
    String userpass = username + ":" + password;  
    String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes()));  
   
    OkHttpClient client = new OkHttpClient();
    Response response ;
    Request request = new Request.Builder()
                     .url(url)
                     .addHeader("Authorization", basicAuth)
                     .build();
    response = client.newCall(request).execute();
    
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

     System.out.println(response.body().string());

but its throwing an error saying {"responseStatus":"FAILURE","responseMessage":"Request method 'GET' not supported","errorCodes":null,"errors":[{"type":"METHOD_NOT_SUPPORTED","message":"Request method 'GET' not supported"}],"errorType":"GENERAL"}

can someone please help me to solve this. or if any have any other idea to authenticate a java application using okhttp then please suggest...

like image 276
Sajid Alam Avatar asked Sep 01 '25 05:09

Sajid Alam


1 Answers

You should use the helper classes to avoid most of the logic for username and password.

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Authenticate.java

            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();

Assuming this API is POST and not GET also follow

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostString.java

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))
        .build();
like image 67
Yuri Schimke Avatar answered Sep 02 '25 19:09

Yuri Schimke