gpt4 book ai didi

java - 如何拦截HttpResponse发送的默认200响应?

转载 作者:行者123 更新时间:2023-12-02 10:55:43 24 4
gpt4 key购买 nike

我需要根据标志(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);
}

最佳答案

你应该使用一个库来做到这一点,这比你自己编写网络层更好。可以使用OkHttp来管理Http Request并实现拦截器,参见这个https://github.com/square/okhttp/wiki/Interceptors
您可以编写一个实现Interceptor接口(interface)的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;
}

关于java - 如何拦截HttpResponse发送的默认200响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com