改造不断伪造我的饼干:( Android

FRR*_*FRR 10 cookies session android json retrofit

因此,当我登录到我的服务器端应用程序时,它给了我一个cookie,允许我在未来的请求中说"嘿,这是我".我曾经使用Android的默认HttpClient类做到这一点,并且效果很好.但是我被告知Retrofit要快得多,并且通过实现GSON来避免处理JSON解析,所以我想我会尝试一下.

我构建了我的客户端,我可以发出请求,但是,我的客户端并没有"记住会话密钥,因此我无法做任何事情.有谁知道如何告诉改造"接受和用户cookie为未来的请求"?我迷路了!任何建议都会做:)

public class ApiClient{

    private static final String API_URL = "http://192.168.1.25:8080";

    private static RestAppApiInterface sRestAppService;

    public static RestAppApiInterface getRestAppApiClient() {
        if (sRestAppService == null) {

            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(cookieManager);

            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .build();
            sRestAppService = restAdapter.create(RestAppApiInterface.class);
        }
        return sRestAppService;
    }

}
Run Code Online (Sandbox Code Playgroud)

Jor*_*914 18

您需要设置Cookie持久客户端.既然您正在使用Android并进行改造,我建议使用OKHttp,它可以通过改造和Android线程安全得到更好的支持,其方法如下

//First create a new okhttpClient (this is okhttpnative)
OkHttpClient client = new OkHttpClient(); //create OKHTTPClient
//create a cookieManager so your client can be cookie persistant
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager); //finally set the cookie handler on client

//OkClient is retrofit default client, ofcourse since is based on OkHttClient
//you can decorate your existing okhttpclient with retrofit's okClient
OkClient serviceClient = new OkClient(client);

//finally set in your adapter
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("Some eNdpoint")
            .setClient(serviceClient)
            .build();
Run Code Online (Sandbox Code Playgroud)

使用Okhttp而不是defaultHttpClient(通过apache)的关键是okhttp是android的线程安全,并且更好地支持改造.

记住,如果你创建另一个适配器,你需要设置相同的客户端,也许如果你在客户端实例上实现单例,你将对所有请求使用相同的一个,保持在相同的上下文中

我希望这会有所帮助,最好


Shi*_*hae 17

如果您使用Retrofit 2,您可以添加库:

compile "com.squareup.okhttp3:okhttp-urlconnection:3.2.0"
Run Code Online (Sandbox Code Playgroud)

然后在创建OkHttp客户端时使用以下代码管理cookie:

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(new JavaNetCookieJar(cookieManager));
Run Code Online (Sandbox Code Playgroud)