【发布时间】:2016-12-21 02:02:02
【问题描述】:
我熟悉如何在 Retrofit2 中使用动态 URL,但在请求中发送用户名和密码时遇到问题。 webAPI 通过输入 URL 来工作,屏幕上会出现登录提示,输入用户名和密码,验证后会显示 JSON 响应。该接口是为动态 URL 定义的:
@GET
public Call<User> getJSON(@Url String string);
我的要求如下:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginService service = retrofit.create(LoginService.class);
Call<User> call = service.getJSON("https://username:password@api.url.com/");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
System.out.println("Response status code: " + response.code());
我确定 URL 是正确的,因为它在浏览器中有效,但我不断收到错误,用户名和密码不正确?
I/System.out: Response status code: 401
此外,据我所知,我只能使用@GET 而不是@POST,因为每当我尝试@POST 时,响应代码都是:
I/System.out: Response status code: 405
起初我尝试使用编码标志遵循类似于this post 的内容,因为它是如何将@PATH 和@URL 与Retrofit2 一起使用但没有任何成功的示例。这就是为什么我尝试在 URL 前加上 username:password@ 的原因。大多数其他示例都使用@POST 方法。
关于如何进行身份验证的任何反馈或想法?谢谢
【问题讨论】:
标签: android json basic-authentication retrofit2