基本身份验证用于JAVA应用程序,使用OkHttp。

huangapple go评论68阅读模式
英文:

Basic Authentication for JAVA Application using OkHttp

问题

以下是翻译好的部分:

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

String url = "我的应用程序 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("意外的代码 " + response);

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

但是它抛出了一个错误,错误信息如下:

{"responseStatus":"FAILURE","responseMessage":"请求方法 'GET' 不受支持","errorCodes":null,"errors":[{"type":"METHOD_NOT_SUPPORTED","message":"请求方法 'GET' 不受支持"}],"errorType":"GENERAL"}

请问是否有人可以帮助我解决这个问题?或者如果有其他方法可以使用 OkHttp 对 Java 应用进行身份验证,那么请提供建议…

英文:

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...

答案1

得分: 3

你应该使用辅助类来避免大部分用户名和密码逻辑。

链接: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();
英文:

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

答案2

得分: 0

你已经完全正确了。只需要进行一个小的修正:

String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));

也就是说,你只需要在 .addHeader("Authorization", basicAuth) 部分中删除多余的 ':',因为这已经在其中得到了处理。

英文:

You had it all right already. Just a small fix needed:

String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));

i.e you just need to remove extra ':' as it's already taken care of in .addHeader("Authorization", basicAuth) part.

huangapple
  • 本文由 发表于 2020年9月22日 17:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64007100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定