OkHTTPClient将cookie传递给Webview

时间:2016-01-07 19:33:59

标签: android webview okhttp

我通过OKHttpClient帖子以用户身份登录,我想与webview共享cookie。

3 个答案:

答案 0 :(得分:10)

使用OkHttp 3.0,您可以使用类似于与HttpURLConnection共享的方法,方法是创建使用webkit cookie存储的WebkitCookieManagerProxy。改编自Pass cookies from HttpURLConnection (java.net.CookieManager) to WebView (android.webkit.CookieManager)

client = new OkHttpClient.Builder().cookieJar(proxy).build();

然后在构建OkHttpClient时添加代理实例作为cookieJar。

public class PowersScreen extends Screen {

public PowersScreen(Game game) {
    super(game);
    // TODO Auto-generated constructor stub
}

Graphics g = game.getGraphics();

public static int choice1 = 3;

int canvasW = g.canvasWidth();
int canvasH = g.canvasHeight();
Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
int rectW = 100;
int rectH = 100;
int left = centerOfCanvas.x - (rectW / 2);
int top = centerOfCanvas.y - (rectH / 2);
int right = centerOfCanvas.x + (rectW / 2);
int bottom = centerOfCanvas.y + (rectH / 2);

static Image chosen_one;

static String chosen_text = "hi";

int left_side_popcornX = g.canvasWidth() / 4 - (Assets.happyPopcorn.getWidth() / 2);
int right_side_popcornX = 3 * g.canvasWidth() / 4 - (Assets.happyPopcorn.getWidth() / 2);

static String back = App.getContext().getString(R.string.back);
static String next = App.getContext().getString(R.string.next);
static String choose_pwrup_1 = App.getContext().getString(R.string.choose_pwrup_1);
static String pwr1 = App.getContext().getString(R.string.power1);
static String pwr2 = App.getContext().getString(R.string.power2);
static String pwr3 = App.getContext().getString(R.string.power3);
static String pwr4 = App.getContext().getString(R.string.power4);
static String pwr5 = App.getContext().getString(R.string.power5);
static String pwr6 = App.getContext().getString(R.string.power6);
static String pwr7 = App.getContext().getString(R.string.power7);
static String pwr8 = App.getContext().getString(R.string.power8);

Rect rect1 = new Rect(0, 0, g.canvasWidth(), g.canvasHeight() / 8);
Rect rect2 = new Rect(left, top+100, right, bottom+100);
Rect rect3 = new Rect(left, top-100, right, bottom-100);
Rect info = new Rect(left_side_popcornX-10, (6 * g.canvasHeight() / 8), right_side_popcornX + Assets.happyPopcorn.getWidth() + 10, (7 * g.canvasHeight() / 8));

@Override
public void update(float deltaTime) {
    Graphics g = game.getGraphics();
    List<TouchEvent> touchEvents = game.getInput().getTouchEvents();

    int len = touchEvents.size();
    for (int i = 0; i < len; i++) {
        TouchEvent event = touchEvents.get(i);
        if (event.type == TouchEvent.TOUCH_UP) {

       int x2 = event.x;
       int y2 = event.y;

       if (rect2.contains(x2, y2)) {
           game.setScreen(new MainMenuScreen(game));
       }

       if (rect3.contains(x2, y2)) {
           game.setScreen(new PowersScreen2(game));
       }

       if (x2 >= left_side_popcornX && x2 < (left_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 2 * g.canvasHeight() / 8 && y2 < (2 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //first popcorn
           choice1 = 3;
       }

       if (x2 >= left_side_popcornX && x2 < (left_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 3 * g.canvasHeight() / 8 && y2 < (3 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //second popcorn
           choice1 = 6;
       }
       if (x2 >= left_side_popcornX && x2 < (left_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 4 * g.canvasHeight() / 8 && y2 < (4 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //third popcorn
           choice1 = 9;
       }
       if (x2 >= left_side_popcornX && x2 < (left_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 5 * g.canvasHeight() / 8 && y2 < (5 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //fourth popcorn
           choice1 = 12;
       }
       if (x2 >= right_side_popcornX && x2 < (right_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 2 * g.canvasHeight() / 8 && y2 < (2 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //sixth popcorn
           choice1 = 15;
       }
       if (x2 >= right_side_popcornX && x2 < (right_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 3 * g.canvasHeight() / 8 && y2 < (3 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //seventh popcorn
           choice1 = 18;
       }
       if (x2 >= right_side_popcornX && x2 < (right_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 4 * g.canvasHeight() / 8 && y2 < (4 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //eighth popcorn
           choice1 = 21;
       }
       if (x2 >= right_side_popcornX && x2 < (right_side_popcornX + Assets.happyPopcorn.getWidth())
               && y2 >= 5 * g.canvasHeight() / 8 && y2 < (5 * g.canvasHeight() / 8 + Assets.happyPopcorn.getHeight())) {
           //ninth popcorn
           choice1 = 24;
       }                    
        }
    }
}

@Override
public void paint(float deltaTime) {
    // TODO Auto-generated method stub
    Paint paint = new Paint();
    paint.setTextSize(20);
    paint.setTextAlign(Align.CENTER);
    paint.setColor(Color.YELLOW);
    paint.setTypeface(Assets.myFont);
    paint.setStyle(Style.STROKE);

    g.clearScreen(Color.rgb(51, 51, 255));

    g.drawRectText(choose_pwrup_1, rect1, paint);
    g.drawImage(PowersScreen.getDecodedChoice(), (g.canvasWidth() / 2) - (CustomizeScreen.getDecodedChoice().getWidth() / 2), g.canvasHeight() / 8);
    g.drawRectText(back, rect2, paint);
    g.drawRectText(next, rect3, paint);

    g.drawRectText(chosen_text, info, paint);
    g.drawRect(info, paint);

    g.drawImage(Assets.powerup_speedup, left_side_popcornX, 2 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_stopall, left_side_popcornX, 3 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_clearall, left_side_popcornX, 4 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_doublepoints, left_side_popcornX, 5 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_regainheart, right_side_popcornX, 2 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_nolostheart, right_side_popcornX, 3 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_nobadpopcorn, right_side_popcornX, 4 * g.canvasHeight() / 8);
    g.drawImage(Assets.powerup_stopboss, right_side_popcornX, 5 * g.canvasHeight() / 8);
}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

@Override
public void backButton() {
    // TODO Auto-generated method stub
    game.setScreen(new PowersExplainScreen(game));
}

public static Image getDecodedChoice() {
    if (choice1 == 3) {
        chosen_one = Assets.powerup_speedup;
        chosen_text = pwr1;
    }
    if (choice1 == 6) {
        chosen_one = Assets.powerup_stopall;
        chosen_text = pwr2;
    }
    if (choice1 == 9) {
        chosen_one = Assets.powerup_clearall;
        chosen_text = pwr3;
    }
    if (choice1 == 12) {
        chosen_one = Assets.powerup_doublepoints;
        chosen_text = pwr4;
    }
    if (choice1 == 15) {
        chosen_one = Assets.powerup_regainheart;
        chosen_text = pwr5;
    }
    if (choice1 == 18) {
        chosen_one = Assets.powerup_nolostheart;
        chosen_text = pwr6;
    }
    if (choice1 == 21) {
        chosen_one = Assets.powerup_nobadpopcorn;
        chosen_text = pwr7;
    }
    if (choice1 == 24) {
        chosen_one = Assets.powerup_stopboss;
        chosen_text = pwr8;
    }
    return chosen_one;
}
}

答案 1 :(得分:2)

此链接有所帮助,但我必须为我的用例修改一些内容:http://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/

以下代码有效:

webView = (WebView) findViewById(R.id.webView);    
WebSettings webSettings = webView.getSettings();

//enable javascript...
webSettings.setJavaScriptEnabled(true);

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progress.dismiss();
    }

    @SuppressWarnings("deprecation")
    @Override
    public WebResourceResponse shouldInterceptRequest(@NonNull WebView view, @NonNull String url) {
        return handleRequestViaOkHttp(url);
    }
});

webView.loadUrl("MY_URL.COM");

然后执行基本身份验证的代码+使用OkHTTPClient处理拦截webview请求。

@NonNull
private WebResourceResponse handleRequestViaOkHttp(@NonNull String url) {
    try {
        OkHttpClient client = new OkHttpClient();

        client.setAuthenticator(new Authenticator() {

            //for basic authorization...
            @Override
            public Request authenticate(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
                String credential = Credentials.basic(CommonResource.HEADER_USERNAME, CommonResource.HEADER_PASSWORD);
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
                return null;
            }
        });

        final Call call = client.newCall(new Request.Builder()
            .url(url)
            .build()
        );

        final Response response = call.execute();

        return new WebResourceResponse("text/html", "UTF-8", response.body().byteStream());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

答案 2 :(得分:0)

如果您只关心OkHttp + WebView,那么它可能会像这样简单:

class WebkitCookieManager (private val cookieManager: CookieManager) : CookieJar {

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookies.forEach { cookie ->
            cookieManager.setCookie(url.toString(), cookie.toString())
        }
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> =
        when (val cookies = cookieManager.getCookie(url.toString())) {
            null -> emptyList()
            else -> cookies.split("; ").mapNotNull { Cookie.parse(url, it) }
        }
}

....


Usage:
 1. OkHttp
OkHttpClient.Builder().cookieJar(webkitCookieManager)

 2. WebView
CookieManager.getInstance().setCookie()

如果不使用HttpURLConnection,则无需支持。