首先,我希望使用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应用程序的任何其他想法,那么请建议...
发布于 2020-09-23 07:48:23
您应该使用帮助器类来避免用户名和密码的大部分逻辑。
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
假设此API是POST,而不是GET,也是如此
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))
.build();
https://stackoverflow.com/questions/64007100
复制相似问题