使用OkHttp进行JAVA应用程序的基本身份验证

问题描述

首先,我想使用OkHttp对我的Java应用程序进行身份验证,然后在身份验证之后,响应返回一个会话ID(密钥),我希望在后续的API调用中使用该会话ID。下面是我用来实现此目的的代码

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

但是它抛出一个错误说 {“ responseStatus”:“ FAILURE”,“ responseMessage”:“不支持请求方法'GET'”,“ errorCodes”:null,“ errors”:[{“ type”:“ METHOD_NOT_SUPPORTED”,“ message”:“请求方法'不支持'GET'“]},” errorType“:” GENERAL“}

有人可以帮我解决这个问题吗?或者,如果有任何其他想法可以使用okhttp对Java应用程序进行身份验证,则建议...

解决方法

您应该使用帮助程序类来避免用户名和密码的大部分逻辑。

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

假设此API是POST而不是GET

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