代码之家  ›  专栏  ›  技术社区  ›  Tanvir Durlove

为什么服务器将应用程序检测为机器人,而不是android版本?

  •  1
  • Tanvir Durlove  · 技术社区  · 7 年前

    2 回复  |  直到 7 年前
        1
  •  3
  •   Faruk    7 年前

    也许你可以用 user-agent 标题

    您可以插入自定义头作为所有http请求的默认头 OkHttpClient

    例如,要添加的自定义标题为:

    'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    

    那么您的改装代码应该是这样的:

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
    
                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"); // <-- this is the important line
    
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
    });
    OkHttpClient mClient = httpClient.build();
    
    Gson gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .create();
    
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(YOUR_BASE_URL)
            .client(mClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    
        2
  •  1
  •   Bill O'Neil    7 年前

    Logger log = LoggerFactory.getLogger(HttpClient.class);
    HttpLoggingInterceptor loggingInterceptor =
        new HttpLoggingInterceptor((msg) -> {
            log.debug(msg);
    });
    loggingInterceptor.setLevel(Level.BODY);
    
    // pass this client into Retrofit
    OkHttpClient networkInterceptorClient = new OkHttpClient.Builder()
        .addNetworkInterceptor(HttpClient.getLoggingInterceptor())
        .build();
    

    这应该会让你 detailed OkHttp logging 包括正在发送的所有标头。然后,您可以添加一个拦截器来覆盖每个HTTP请求的用户代理,并选择一个基于浏览器的拦截器,使服务器认为您正在使用web浏览器。

    如果这不起作用,请继续比较不同的标头,并查看是否可以使用创建请求 cURL