如何在AsyncHttpClient中设置用户代理?

时间:2019-05-25 18:04:12

标签: java android

在我的应用中,我正在使用YouTube。我正在请求在移动视图中需要的页面。像这样... http://m.youtube.com?persist_app=1&app=m 如果我将该链接输入到网络浏览器中,那么我将被锁定在YouTube页面上的移动视图中(在Web浏览器中)。我想对AsyncHttpClient做同样的事情。如果我使用的是网络视图,我知道我可以做到。.

WebSettings ws = wv.getSettings();
ws.setUserAgentString("Foo/");

现在如何使用AsyncHttpClient完成此操作?

我已经尝试过了,但是没有用

public void myAsyncHttpClient(String url) {
    AsyncHttpClient client = new AsyncHttpClient();

    client.addHeader("User-Agent", "Foo/");
    client.setUserAgent("Foo/");

    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

            urlHTMLCode = new String(responseBody);

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

只需使用

AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent(UserAgentString).build();
AsyncHttpClient asyncHttpClient = new AsyncHttpClient(cf);

示例代码>

public void myAsyncHttpClient(String url) {

    AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent("User-Agent").build();
    AsyncHttpClient client = new AsyncHttpClient(cf);

    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            urlHTMLCode = new String(responseBody);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}