DEV Community

CodeCat1024
CodeCat1024

Posted on

Send and handle HTTP request in Java

Send requests

You can send requests by listed ways.

Tag a or broswer and so son

They are all make a GET request method.

Image description

Postman

You can use Postman to make any requests.

Image description

Form Input

You can use any request methods by using attribute method.

And the attribute action represent the URI where the form will sumbit.

<form action="postGetParameter" method="post">
    <input type="text" name="userId">
    <input type="password" name="password">
    <input type="submit" value="sumbit">
</form>
Enter fullscreen mode Exit fullscreen mode

Ajax

We needn't form tag by this way.

Because you can set the method and the action in JS code.

<input type="text" id="userId">
<input type="text" id="classId">
<input type="button" value="sumbit" id="submit">
Enter fullscreen mode Exit fullscreen mode
let userIdInput = document.querySelector("#userId");
let classIdInput = document.querySelector("#classId");
let button = document.querySelector("#sumbit");
button.onclick = function(){
    $.ajax({
        type: 'post',
        url: 'path',
        data: JSON.stringify({
            userId: userIdInput.value,
            classId: classIdInput.value
        }),
        success: function(body){
            console.log(body);
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

Handle requests in Java

We can use three classes to handle requests in servlet.

HttpServlet

class User {
    //You must need to note the types.
    //If you wrote a String, but you send a int, it will throw a exception.
    public String userId;
    public String classId;
}

@WebServlet("/path")
public class HelloServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //You must to comment this method otherwise your codes will goes wrong
       //super.doGet(req, resp);

       //And you must add the setContentType method if you want to print in Chinese.
       resp.setContentType("text/html; charset=utf8");
       //You can use this method to print something to the console of the broswer
      resp.getWriter().write("Hello Servlet");


       //HANDLE THE STRING
       String userId = req.getParameter("userId");
       String classId = req.getParameter("classId");
       resp.getWriter().write("userId: " + user.userId + "classId: " + user.classId);

        //HANDLE THE JSON STRING
        //The first parameter, you can give a String or a InputStream Object
        //The second parameter, present what object you want t make and then you will get a class.
        User user = objectMapper.readValue(req.getInputStream(), User.class);
        resp.getWriter().write("userId: " + user.userId + "classId: " + user.classId);
    }
}
Enter fullscreen mode Exit fullscreen mode

HttpServletRequest and HttpServletResponse

Servlet provides two classes let we to operate attributes of Request and Response.

They have many methods provied let you to operate.

Image description

You can search these methods in google.


body format

The data body have three formats when you use post method.

x-www-form-unlencoded

form-data

json

Top comments (0)