Send and handle HTTP request in Java
Tags: java
Published: 2023-02-23 13:50:47

# 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zy3tdiollg3laogck8of.png)


## Postman

You can use Postman to make any requests.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57v3zqnfb2kieqdhuff6.png)



## Form Input

You can use any request methods by using attribute method.

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

```HTML
<form action="postGetParameter" method="post">
    <input type="text" name="userId">
    <input type="password" name="password">
    <input type="submit" value="sumbit">
</form>
```

## Ajax

We needn't form tag by this way.

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

```HTML
<input type="text" id="userId">
<input type="text" id="classId">
<input type="button" value="sumbit" id="submit">
```

```JavaScript
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);
        }
    });
}
```

---

# Handle requests in Java

We can use three classes to handle requests in servlet.

## HttpServlet


```java
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);
    }
}
```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bokxnvmw3ct099mts5em.png)


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