Get response header OkHttp - java

I need to check response header of HTTP request using OkHTTP library. before loading data I need to check it's last update time. The problem in that that the response body is about 2 MB so I need to get only Last-Modified header. Is it possible to load only response header without response body to increase the speed of the program`s RESTful actions?

You can send a HTTP HEAD request which only retrieves the headers. You only need to check if your server application supports HEAD requests.
The HEAD method is identical to GET except that the server MUST NOT
return a message-body in the response. The metainformation contained
in the HTTP headers in response to a HEAD request SHOULD be identical
to the information sent in response to a GET request. This method can
be used for obtaining metainformation about the entity implied by the
request without transferring the entity-body itself. This method is
often used for testing hypertext links for validity, accessibility,
and recent modification. (http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)
Example for OkHttp:
String url = ...
Request request = new Request.Builder().url(url).head().build();

The response body is streamed, so you can make the regular request, read the headers, and then decide whether or not to consume the body. If you don’t want the body, you can close() it without much waste.
There is a slight cost to the server to serve a response that might be abandoned. But the overall cost will be lower than making a HEAD and then a GET request unless you expect abandon a significant fraction (say > 90%) of requests.

Related

Java Server Side: send Http POST response - status only

Some third party is sending an Http Post request whenever something changes in their DB (e.g. when a contact has been updated, they send the contactID and 'contact_updated'). I have build a socket listener that catches those requests and is able to parse the information. However, I just can't get it to work to send back a response with the status '200 - OK'. Thus, the server on the client side keeps on trying (four times or so) to re-send the request.
Is there any, simple way to just send the response status without the need of adding external libs etc.?
It should be enough to send the string HTTP/1.1 200 OK back in your socket-listener.
If you have troubles, you can check out this answer, it shows how to use a HttpServer in Java just via plain JavaSE features.
Use
response.setStatus(HttpServletResponse.SC_OK);
to set the status code in your response header.
You may also set the content type.
response.setContentType("text/html;charset=UTF-8");

HTTP: what is the correct way to send "retry/redirect" response

I need to force the client to retry its request (meaning to send the same request one more time). What I'm thinking of is a response with status-code 307 and header Location: <original-url> (that's good enough for now, unless there's a better way).
My question is, from HTTP specification point of view, what is the correct value for Location in this specific context. Or more specifically in Java having request of type HttpServletRequest, which one should I use: getRequestURI (Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request) or getRequestURL (Reconstructs the URL the client used to make the request containing protocol, server name, port number, and server path, but it does not include query string parameters).
Any other suggestion/comment is appreciated.
getRequestURL() returns complete URL used by the client where as getRequestURI() returns just the basic path resides in server.
i am using this technique to redirect with a response status this is my code this is useful:-
httpServletResponse.reset();
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpServletResponse.setHeader("SERVER-RESPONSE", "bad request");
return;
and also you can set headers in response.
I believe a redirect is the wrong status code in the first place.
Isn't this what 503 is for? (https://www.greenbytes.de/tech/webdav/rfc7231.html#status.503)

PUT response code with 204

My PUT and POST are same, so I am using PUT operation. Here I need to send response body data when PUT successful e.g. either new data insert into Cassandra or update existing record.
So, what response code should I use in this case.. code 204 I am using for successful PUT with response body, but it automatic convert into 200 code while testing with POSTMAN. so what should I use here.
According to this:
If the target resource does not have a current representation and the
PUT successfully creates one, then the origin server MUST inform the
user agent by sending a 201 (Created) response. If the target
resource does have a current representation and that representation is
successfully modified in accordance with the state of the enclosed
representation, then the origin server MUST send either a 200 (OK) or
a 204 (No Content) response to indicate successful completion of the
request.
Based on this (and agreeing with Hank), if you have an entity with your response, you should use 201.

RESTful API - chunked response for bulk operation

I work on a REST-like API that will support bulk operations on some resources. As it may take some time to finish such a request, I would like to return statuses of the operations in a chunked response. The media type should be JSON. How to do it with JAX-RS?
(I know that there is StreamingOutput, but it needs to manually serialize the data.)
Chunked Transfer encoding is usually used in cases where the content length is unknown when the sender starts transmitting the data. The receiver can handle each chunk while the server is still producing new ones.
This implies the the server is sending the whole time. I don't think that it makes too much sense to send I'm still working|I'm still working|I'm still working| in chunks and as far as I know chunked transfer-encoding is handled transparently by most application servers. They switch automatically when the response is bigger then a certain size.
A common pattern for your use case looks like this:
The client triggers a bulk operation:
POST /batch-jobs HTTP/1.1
The server creates a resource which describes the status of the job and returns the URI in the Location header:
HTTP/1.1 202 Accepted
Location: /batch-jobs/stats/4711
The client checks this resource and receives a 200:
GET /batch-jobs/stats/4711 HTTP/1.1
This example uses JSON but you could also return plain text or add caching headers which tell the client how long he should wait for the next poll.
HTTP/1.1 200 OK
Content-Type: application/json
{ "status" : "running", "nextAttempt" : "3000ms" }
If the job is done the server should answer with a 303 and the URI of the resource he has created:
HTTP/1.1 303 See other
Location: /batch-jobs/4711

An easy way to detect the end of http response (raw socket, java)?

I want to retrieve the server's response as is, with all headers. The first thing that comes to mind is to use raw sockets. As I have learned from the search, there are 3 ways to indicate the end of response:
(1) closing the connection;
(2) examining Content-Length;
(3) getting all chunks in the case of Transfer-Encoding: Chunked.
There is also
(4) the timeout method: assume that the timeout means end of data, but the latter is not really reliable.
I want a general-case solution and do not want to
add a Connection: close line to the request itself.
In addition, it is recommended to use an existing library rather than re-invent the wheel.
Question:
How do I use an existing package, preferably, something already present in Android, to detect the end of HTTP response while having access (without interference) to the raw data stream?
UPD: forgot to mention that the HTTP request is given to me as a sequence of bytes. Yes, it is for testing.
PS
relevant reading:
End of an HTTP Response
Detect the end of an HTTP Request in Java
Detect end of HTTP request body
How HTTP Server inform its clients that the response has ended
Proper handling of chuncked Http Response within Socket
Detect the end of a HTTP packet
Android socket & HTTP response headers
Java HTTP GET response waits until timeout
I suggest to use a the Apache HTTP client package (http://hc.apache.org/httpclient-3.x/ ) so you don't need to implement all the finicky details of the HTTP protocol.
The Apache Http Client will give you access to the headers and their content, which may be enough for you.
If you really need access to the actual character sequence sent by the server (e.g. for debugging purposes), you could then intercept the communication by replacing the connection socket factory with your own to create "intercepting" sockets which store all data transferred in a buffer where your code can access it later on. See http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/connmgmt.html#d5e418

Categories