【问题标题】:How to intercept the default 200 response sent from HttpResponse?如何拦截 HttpResponse 发送的默认 200 响应?
【发布时间】:2018-08-09 15:06:45
【问题描述】:

我需要根据标志(loginStatus)发送响应,但是,在此之前,会发送默认的 200 响应。如何拦截响应?

private void handlePost(HttpRequest request, HttpResponse response) {
    response.setHeader("Content-Type", "text/html");
    HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();

   **// Handling the request here ......**

    Handler mainHandler = new Handler(context.getMainLooper());

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            HttpEntity respEntity = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    final InputStream in = getContext().getAssets().open( "home.html" );

                    IOUtils.copy(in, writer);
                    writer.flush();
                }
            });
            response.setHeader("Content-Type", "text/html");
            response.setEntity(respEntity);

          **//the loginStatus value is asynchronous so waiting for 5000**

            if(loginStatus){
         **// set status code 201**
                response.setStatusCode(HttpStatus.SC_CREATED);
            } else {
         **// set status code 501**
                response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
            }
        }
    };

    mainHandler.postDelayed(runnable, 5000);
}

【问题讨论】:

  • 1) 不要自己编写网络层 2) 使用改造之类的库 3) 实现一个拦截器

标签: java android androidhttpclient


【解决方案1】:

您应该使用库来执行此操作,这比自己编写网络层要好。 你可以使用 OkHttp 来管理 Http Request 并实现一个拦截器,看这个https://github.com/square/okhttp/wiki/Interceptors
你可以写一个实现Interceptor接口的CustomClass,重写这个方法

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);
    if (response.code() = 200) {
        //Do what you want
    }
    Log.d(TAG, "INTERCEPTED:$ " response.toString());
    return response;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2022-07-12
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多