Hot to get the 200 response code inside the Volley response block [duplicate] - android-volley

This question already has answers here:
Http Status Code in Android Volley when error.networkResponse is null
(8 answers)
Closed 6 years ago.
My app uses volley library for networking operation. I want to get the response code (that may be 200 or 401) inside onResponse() method. How can i achieve that?

you can make a custom request and override:
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
if (response.statusCode == 200) {
//do smth
} else if (response.statusCode == 401) {
//do smth else
}
return super.parseNetworkResponse(response);
}
this way you will still receive the same data in your callbacks but special cases typical for the request you can handle within the request itself.

Related

CompletableFuture<ResponseEntity> Status Code Expectations

So, I have created a Controller within which I have a POST endpoint like so:
#PostMapping("/foo/{some-field}")
public CompletableFuture<ResponseEntity> foo() {
//Do some operations...
...
if(doesNotExist({some-field})) {
return CompletableFuture.completedFuture(ResponseEntity.notFound().build());
}
return CompletableFuture.completedFuture(ResponseEntity.ok().build());
}
Now I would expect that if doesNotExist({some-field}) == true, I'd be prompted with a NOT_FOUND status.
I however end up with a OK status every time around.
Are my expectations wrong in regards to how the ResponseEntity is returned?
Any suggestions how to get the NOT_FOUND status if doesNotExist({some-field}) == true would be much appreciated.
Edit/Update
From the comments I assume my initial question was a little to light, so let me explain when I see this failing, as it seems that my assumption of what the ResponseEntity.HttpStatus would be is correct.
I have made small adjustments to the code block above.
The situation where I receive an unexpected status is when I try to test the NOT_FOUND situation through Spring Cloud Contracts.
An example of the contract looks as follows:
Contract.make {
request {
method 'POST'
url "/foo/SomeNoneExistingField"
body("{}")
headers {
contentType applicationJson()
}
}
response {
status HttpStatus.NOT_FOUND.value()
}
}
So the {some-field} in this contract is set to a field which ensure that doesNotExist({some-field}) == true. I see it end up in this block if I am debugging my code as well.
Nonetheless, the Spring Cloud Contract test status that the response.status == OK i.o. NOT_FOUND.
Might I be using Spring Cloud Contracts incorrectly if my assumption on the HttpStatus returned from a CompletableFuture is correct?
Any help/advice is (again) much appreciated.
There is nothing complex here and it should work as expected.
It is happening may be because of {some-state} is not true so every time it is going to else block.
Ensure that {some-state} evaluation returns true and compiler enters into if block.
if({some-state}) {
return CompletableFuture.completedFuture(ResponseEntity.notFound().build());
}
Ok, I figured out the issue I was experiencing.
Credits to #Marcin Grzejszczak for putting me on the right track in regards to configuration.
What I was missing from my contracts to be able to handle async results, like a CompletableFuture, was that I needed to add async() to my result.
Thus, a contract like so:
Contract.make {
request {
method 'POST'
url "/foo/SomeNoneExistingField"
body("{}")
headers {
contentType applicationJson()
}
}
response {
status HttpStatus.NOT_FOUND.value()
async() // <---- This was it!
}
}
Did the trick.

Can I access the request/response body on an ExchangeFilterFunction?

Given an exchange using WebClient, filtered by a custom ExchangeFilterFunction:
#Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request)
.doOnSuccess(response -> {
// ...
});
}
Trying to access the response body more than once using response.bodyToMono() will cause the underlying HTTP client connector to complain that only one receiver is allowed. AFAIK, there's no way to access the body's Publisher in order to cache() its signals (and I'm not sure it'd be a good idea, resource-wise), as well as no way to mutate or decorate the response object in a manner that allows access to its body (like it's possible with ServerWebExchange on the server side).
That makes sense, but I am wondering if there are any ways I could subscribe to the response body's publisher from a form of filter such as this one. My goal is to log the request/response being sent/received by a given WebClient instance.
I am new to reactive programming, so if there are any obvious no-nos here, please do explain :)
Only for logging you could add a wiretap to the HttpClient as desribed in this answer.
However, your question is also interesting in a more general sense outside of logging.
One possible way is to create a duplicate of the ClientResponse instance with a copy of the previous request body. This might go against reactive principles, but it got the job done for me and I don't see big downsides given the small size of the response bodies in my client.
In my case, I needed to do so because the server sending the request (outside of my control) uses the HTTP status 200 Ok even if requests fail. Therefore, I need to peek into the response body in order to find out if anything went wrong and what the cause was. In my case I evict a session cookie in the request headers from the cache if the error message indicates that the session expired.
These are the steps:
Get the response body as a Mono of a String (cf (1)).
Return a Mono.Error in case an error is detected (cf (2)).
Use the String of the response body to build a copy of the original response (cf (3)).
You could also use a dependency on the ObjectMapper to parse the String into an object for analysis.
Note that I wrote this in Kotlin but it should be easy enough to adapt to Java.
#Component
class PeekIntoResponseBodyExchangeFilterFunction : ExchangeFilterFunction {
override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> {
return next.exchange(request)
.flatMap { response ->
// (1)
response.bodyToMono<String>()
.flatMap { responseBody ->
if (responseBody.contains("Error message")) {
// (2)
Mono.error(RuntimeException("Response contains an error"))
} else {
// (3)
val clonedResponse = response.mutate().body(responseBody).build()
Mono.just(clonedResponse)
}
}
}
}
}

Can an Owin Middleware return a response earlier than the Invoke method returns?

I have the following middleware code:
public class UoWMiddleware : OwinMiddleware
{
readonly IUoW uow;
public UoWMiddleware(OwinMiddleware next, IUoW uow) : base(next)
{
this.uow = uow;
}
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch
{
uow.RollBack();
throw;
}
finally
{
if (uow.Status == Base.SharedDomain.UoWStatus.Running)
{
var response = context.Response;
if (response.StatusCode < 400)
{
Thread.Sleep(1000);
uow.Commit();
}
else
uow.RollBack();
}
}
}
}
Occasionally we observe that the response returns to client before calling uow.Commit() via fiddler. For example we put a break point to uow.Commit and we see the response is returned to client despite that we are on the breakpoint waiting. This is somewhat unexpected. I would think the response will strictly return after the Invoke method ends. Am I missing something?
In Owin/Katana the response body (and, of course, the headers) are sent to the client at the precise moment when a middleware calls Write on the Response object of the IOwinContext.
This means that if your next middleware is writing the response body your client will receive it before your server-side code returns from the call to await Next.Invoke().
That's how Owin is designed, and depends on the fact that the Response stream may be written just once in a single Request/Response life-cycle.
Looking at your code, I can't see any major problem in such behavior, because you are simply reading the response headers after the response is written to the stream, and thus not altering it.
If, instead, you require to alter the response written by your next middleware, or you strictly need to write the response after you execute further logic server-side, then your only option is to buffer the response body into a memory stream, and than copy it into the real response stream (as per this answer) when you are ready.
I have successfully tested this approach in a different use case (but sharing the same concept) that you may find looking at this answer: https://stackoverflow.com/a/36755639/3670737
Reference:
Changing the response object from OWIN Middleware

Returning error from SignalR server method

I am new to SignalR and there is a small detail I can't get my head around.
My SignalR hub include many channels and the clients can join one or many of these channels via a server method:
joinChannel(string channelName)
What I don't understand is what this method should return.
If it were a normal "RPC" method I would return a status (200 - Ok, 404 - Not found, 403 - Forbidden etc) via IHttpActionResult.
How do I indicate success/failure in SignalR?
What determines if the reply gets to .done or .fail in the client?
Update
Currently my method returns a non-zero value in case of error.
int joinChannel(string channelName) {
...
return errorCode;
}
This works but it create unnecessarily complicated code in the client
hubProxy.server.joinChannel('channel1')
.done(function (result) {
if (result != 0) {
// error handling
}
})
.fail(function (error) {
// error handling
});
To confirm that your action was successfully performed, you can have a client method call. So, basically it would look like this:
public void ServerMethod(argumentList)
{
if (/* server code executed successfully */)
Clients.Caller.onSuccess(arguments);
else Clients.Caller.onFailure(arguments);
}
What this piece of code does is to notify the caller of the server method of a success/failure by calling a client method - method defined in JavaScript. You can also have a method executed on All clients, or only on specific users.
Since it is not an RPC mechanism, I think this is the closest thing you can do to simulate a return type in SignalR.
Hope this helps!
Best of luck!
What about
HubException in
Microsoft.AspNetCore.SignalR.
This is available in ASP.NET Core.
This exception is thrown on the server and sent to client. You can also derive from that class to put your own information in it.

Jquery .get function returns [Object object] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
function getsession(){
var data = $.get('../session', function(data)
{
return data;
});
return data;
}
alert(getsession());
returns [object Object]
I want it to return the data from the GET.
try this instead
function getAndProccessSession(){
$.get('../session', function(returnedSessionData)
{
console.log(returnedSessionData);
});
}
Since the function passed $.get is executed asynchronously after the HTTP request is finished, you can't get a return variable.
After $("#openSession").append(data), you could also alert(data).
if you want to see the data and your using firefox maybe some others you can use
alert(getsession().toSource());
that way you can see the object that your getting back but if you know the data items you can target them direct
alert(getsession().someItemInTheObject);
if you are using google chrome you can do a console.log(getsession()) within your code and then press ctr+shift+c to open google chrome dev tools, then go to the console tab, you can see the object there and you can click it to view its internal properties values

Resources