我需要基于标志(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);
}
答案 0 :(得分: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;
}