Answer the question
In order to leave comments, you need to log in
Retrofit how to log in?
There is a rest service, authorization works like this:
restservice.ru/api/login?username=abc&password=12345
further it is supported through cookies:
JSESSIONID = "BLABLABLA",
Question:
How to log in using Retrofit,
and then substitute cookies received during authorization , in further requests to the service ?
PS Thanks in advance!
Answer the question
In order to leave comments, you need to log in
The documentation tells us this:
A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.
@GET("/user")
Call<User> getUser(@Header("Authorization") String authorization)
public interface KotomatrixService {
@FormUrlEncoded
@POST("http://kotomatrix.ru")
Call<String> login(@Field("login") String login, @Field("password") String pass, @Field("act") String act, @Field("remember") String remember);
}
public class ApiFactory {
private static final int CONNECT_TIMEOUT = 15;
private static final int WRITE_TIMEOUT = 60;
private static final int TIMEOUT = 60;
private static final OkHttpClient CLIENT = new OkHttpClient();
static {
CLIENT.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
CLIENT.setReadTimeout(TIMEOUT, TimeUnit.SECONDS);
}
@NonNull
public static KotomatrixService getKotomatrixService() {
return getRetrofit().create(KotomatrixService.class);
}
@NonNull
private static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl("http://kotomatrix.ru")
.addConverter(String.class, new StringConverter())
.client(CLIENT)
.build();
}
}
public final class StringConverter implements Converter<String> {
@Override
public String fromBody(ResponseBody body) throws IOException {
return body.string();
}
@Override
public RequestBody toBody(String value) {
return RequestBody.create(MediaType.parse("text/plain"), value);
}
}
public class MainActivity extends AppCompatActivity implements Callback<String> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KotomatrixService service = ApiFactory.getKotomatrixService();
Call<String> call = service.login("testUser", "testUser", "login", "true");
call.enqueue(MainActivity.this);
}
@Override
public void onResponse(Response<String> response) {
if (response.isSuccess()) {
// ищем куку и сохраняем
}
}
@Override
public void onFailure(Throwable t) {
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question