Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

android - How to retrieve cookies in Retrofit?

I read about request interceptors and what not but no clue how to really use them to obtain cookies... I am sending the cookie like so from nodejs...

res.cookie('userid', user._id, { maxAge: 86400000, signed: true, path: '/' });

And in my android client - I have this set up so far for my RestApiManager

public class RestApiManager {
  private static final String API_URL = "ip: port";

    private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    //Call interface
    public interface AsynchronousApi {
  //Login User
        @FormUrlEncoded
        @POST("/login")
        public void loginUser(
                @Field("loginName") String loginName,
                @Field("password") String password,
                Callback<UserResponse> callback);
//Profile Picture
        @Multipart
        @POST("/profilePicture")
        public void uploadProfilePicture(
                @Part("photo") TypedFile photo,
                @Part("userId") String userId,
                Callback<UserResponse> callback); //success thumbnail to picasso

    }
    //create adapter
    private static final AsynchronousApi ASYNCHRONOUS_API = REST_ADAPTER.create(AsynchronousApi.class);

    //call service to initiate
    public static AsynchronousApi getAsyncApi() {
        return ASYNCHRONOUS_API;
    }
}

Separate cookie class:

    public class ApiCookie implements RequestInterceptor{
    // cookie use
    private String sessionId;

    public ApiCookie() {

    }

    //COOKIE BELOW
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public void clearSessionId() {
        sessionId = null;
    }


    @Override
    public void intercept(RequestFacade requestFacade) {
        setSessionId();
    }
}

trying to figure out how to obtain the cookie and be able to send it with future requests, so I do not need to include a userId field?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had similar situation in my app. This solution works for me to retrieve cookies using Retrofit. MyCookieManager.java

import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.List;
import java.util.Map;

class MyCookieManager extends CookieManager {

    @Override
    public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
        super.put(uri, stringListMap);
        if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
            for (String string : stringListMap.get("Set-Cookie")) {
                if (string.contains("userid")) {
                    //save your cookie here
                }
            }
    }
}

Here is how to set your cookie for future requests using RequestInterceptor:

 MyCookieManager myCookieManager = new MyCookieManager();
            CookieHandler.setDefault(myCookieManager);
 private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setRequestInterceptor(new RequestInterceptor() {
                        @Override
                        public void intercept(RequestFacade requestFacade) {
                            String userId = ;//get your saved userid here
                            if (userId != null)
                                requestFacade.addHeader("Cookie", userId);
                        }
                    })
            .build();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...