Get form requests from a HTTP request in Java - java

I have created a HTTP server which works perfectly! No problems there,
using Sockets and ServerSockets.
Now I need to make the Form entries - which are done in the web browser and when they are submitted, they are processed by Java.
I've tried making a form, then pressing sumbit, except it's given a 501 error... The first part is 'POST /'. I suppose that means a hidden variable passed... But how do I make the server recognise the hidden variable, and make it process it?
Is there any way to do this?

How you decode the parameters depends on a number of things. If the request is a POST request then the values are part of the request body (this is, the values are sent after a blank link that separates the head and the body of the request). The encoding of the request body is then either "application/x-www-form-urlencoded" or "multipart/form-data". You can read how these two encodings work here: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
I assume that this is a toy project and that you want to write this code yourself. Otherwise there are many server implementations of the HTTP protocol for Java out there...

Related

Using POST method instead of GET in a rest API

Is there a specific scenario where we use a POST instead of GET, to implement the functionality of get operation ?
GET is supposed to get :) and POST is used to mainly add something new or sometimes often used for updates as well (although PUT is recommended in such scenarios). There is no specific scenario where we use a POST instead of a GET, if we require this, that means we are probably doing it wrong, although nothing stops you doing this but this is bad design and you should take a step back and plan your API carefully.
There are 2 important cases for a POST i.e. POST is more secure than a GET and POST can send large amount of data but even with this I won't recommend why one will use POST to simulate a GET behaviour.
Lets understand usage of get and post :
What is GET Method?
It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048 characters. This method must not be used if you have a password or some sensitive information to be sent to the server. It is used for submitting the form where the user can bookmark the result. It is better for data that is not secure. It cannot be used for sending binary data like images or word documents. It also provides $_GET associative array to access all the sent information using the GET method.
What is POST Method?
It appends form-data to the body of the HTTP request in such a way that data is not shown in the URL. This method does not have any restrictions on data size to be sent. Submissions by form with POST cannot be bookmarked. This method can be used to send ASCII as well as binary data like image and word documents. Data sent by the POST method goes through HTTP header so security depends on the HTTP protocol. You have to know that your information is secure by using secure HTTP. This method is a little safer than GET because the parameters are not stored in browser history or in web server logs. It also provides $_POST associative array to access all the sent information using the POST method.
Source: https://www.edureka.co/blog/get-and-post-method/
So both the methods have their specific usage.
POST method is used to send data to a server to create or update a resource.
GET method is used to request data from a specified resource.
If you want to fetch some data you can use the GET method. But if you want to update an existing resource or create any new resource you should use POST. GET will not help you to create/update resources. So exposing the api should be specific to your needs.
UPDATE
So your main question is in what scenario we can use POST to implement the functionality of GET.
To answer that, as you understand what GET and POST does, so with GET request you will only fetch the resource. But with POST request you are creating or updating the resource and also can send the response body containing the form data in the same request response scenario. So suppose you are creating a new resource and the same resource you want to see, instead of making a POST call first and making a GET call again to fetch the same resource will cost extra overhead. You can skip the GET call and see your desired response from the POST response itself. This is the scenario you can use POST instead of making an extra GET call.

Trusting "Content-Type" on File Uploads

If I'm supporting the upload of content (mostly images and video) by my REST API's users, is it safe to trust the Content-Type they declare in (multipart) uploads? Or should I, instead, run some kind of "media type detection" on the content (using, for example, Apache Tika) to ensure that the declared media type corresponds to the detected, actual one? Am I being over-zealous by introducing this media type detection step?
You certainly shouldn't blindly trust the Content-type header, or any other header. These things should be used to inform your decisions about how to process the request. So, Content-type: application/json should allow you to interpret the message body as a json object - that sort of request might then be passed to a JSON deserialiser to bind it to an object.
It would be wrong to ignore the Content-type header just because the request body contains data which looks like something else. If the request is internally inconsistent then it should be rejected. It's one thing not to send a Content-type header but quite another for the header to be wrong.
So, the only situation where you might want to use some sort of automatic detection should be where you have no reasonable information about the content - either Content-Type is very generic (such as "/") or not present at all. In that situation it's worth deciding whether some kind of autodetection is possible or valuable.
Never trust the input which you get from the user. Always run a check in your server side code be it type of file, size of file, etc. Use the REST API or Javascript to make the experience of the user smoother and faster.
You should definitely reject all the requests that are missing Content-Type header (and Content-Length as well) or have it set incorrectly.
It's definitely not about being over-zealous, rather about securing the system. If you have suspicions about the content just check it. But remember to validate the size before checking the content. If you have a proxy server (e.g. nginx) it has appropriate modules to reject requests that are too big.

Return an integer from server to client in response to a REST call

I have a situation where the client (.js) initiates a REST request and it is processed on the server side (.java). After processing, I would like to return a count to the client, which will be shown in a popup box if it is positive. How can such a construction be done? The idea I had was to set a named parameter on the HttpServletResponse object, but even this object is no where in scope in the .js code. Any ideas? I should also clarify that the primary purpose of the REST call is to download a file to the client. Thanks!
Do you want to send two things to your client - sending a file and also additional data? You haven't mentioned what framework (if any) you are using in backend to do this. You can use response header.
From your question, it seems like you don't have a good general-purpose way of responding to client requests on your server. I'd recommend you decide on a data format you'd like to use for all calls (e.g., JSON, XML, etc.) and stick with that across the board.
Once you've made that decision, you can encode your integer using whatever makes sense in your chosen format. For example, in JSON you might return: {"count":6}.

Send a bunch of values from jsp to java code

I have a form on my jsp with fields - Name, IP, username, token.
It is mapped to a table with same column names. I have created a Bean class too.
Now, I am not sure what is an ideal way to send all the parameters from jsp to the java code.
I know few options like -
Create input with type hidden and then set its value in the jsp.
<input type="hidden" id="name" name="name"/>
and then retrieve its value in the code using request.getParameter("name")
Somehow I dont feel this is an ideal way.
Create a JSON with all the values of the input boxes and set the json file as one input and read it on the java code using org.json;
Which one of the two is the better way to do it? Is there any simpler, effective and much better way?
Everything which is built using HTTP methods must send values to the server in one of three places:
Parameters in the url itself (GET requests)
Content in the body of the request (POST requests)
Key-value pairs in the header of the request (HTTP method agnostic)
Any mechanism you use to send a value back to the server (excluding web sockets), no matter what the framework, will use one of these mechanisms underneath.
That being said, use whatever best meets the requirements of your application:
Form-based, GET requests:
are simple to understand
don't require much overhead either on the front-end or back-end
are easy to test (just access the url using the appropriate query string)
Form-based, POST requests:
are also simple to understand
also don't require much overhead either on the front-end or back-end
are not as easy to test (you can't just access the url using the appropriate query string)
Ajax-y, JSON body, POST requests:
are the new hotness
require a bit more front-end work (creating the request in JS and sending it)
don't require the browser to make a full-page request/response

How to get HTTP response through socket in java?

I have written a code to send a HTTP request through a socket in java. Now I want to get the HTTP response that was sent by the server to which I sent HTTP request.
It's not totally clear what you're asking for. Assuming you've written the request to the socket, the next thing you'll want to do is:
Call shutdownOutput() on the socket to tell the server that the request is done (not necessary if you've sent the content length)
Read the response from the socket's input stream, parsing according to the HTTP spec.
This is a bunch of work, so I'd suggest that rather than rolling your own HTTP request logic, use URLConnection which is built-in to Java and includes methods for retrieving the content of a response as well as any headers set by the server.
As Jon said, read the HTTP spec. However Internet protocols are generally line oriented, so you can read the response a line a time. The first line will be the response. Following this will be the headers, one per line (unless there's a continuation). If there's a body one of the headers will the content-type, this will tell you what the content is. If you want to read the content you will need to understand the different ways the content can be sent. There may be a content length header (or not) or the content maybe chunked (can't remember the header off the top of my head). And of course the content may be binary rather than text.
yup!
that's right!
the respond should be clearly readed by the inputstream into
a few chunk of bytes...
thus we could translate it into a readable format.
But that also take longer time.... :(

Categories

Resources