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

使用OkHttp对JAVA应用程序进行基本身份验证,java,okhttp,Java,Okhttp,首先,我想使用OkHttp对我的java应用程序进行身份验证,然后在身份验证之后,响应返回我想在后续API调用中使用的会话ID(密钥)。下面是我用来实现这一点的代码 String url = "my application url"; String username = "xxx"; String password = "zzz"; String userpass = username + &qu

首先,我想使用OkHttp对我的java应用程序进行身份验证,然后在身份验证之后,响应返回我想在后续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”:“Request method'GET'not supported”,“errorCodes”:null,“errors”:[{“type”:“method_not_supported”,“message”:“Request method'GET'not supported”}],“errorType”:“GENERAL”}


有人能帮我解决这个问题吗。或者,如果有人有任何其他想法使用okhttp对java应用程序进行身份验证,那么请建议…

您应该使用helper类来避免用户名和密码的大部分逻辑

假设这个API是POST而不是GET,那么也要遵循它


基本身份验证头是错误的,应该是
“basic:+…
,但这并不能真正解释错误消息。
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))
        .build();