Search code examples
restrequestjsouphttp-deletehttp-put

Does jsoup support restful/rest request


Can you tell me please how to create http(s) request in jsoup with request method PUT or DELETE?

I came across this link: https://github.com/jhy/jsoup/issues/158 but it is few years old, so hopefully there is some restful support implemented in that library.

As far as I can see HttpConnection object I can only use 'get' or 'post' request methods.

http://jsoup.org/apidocs/org/jsoup/helper/HttpConnection.html

http://jsoup.org/apidocs/org/jsoup/Connection.html


Solution

  • Jsoup doesn't support PUT nor DELETE methods. Since it is a parser, it doesn't need to support those operations. What you can do is use HttpURLConnection , which is the same that Jsoup uses underneath. With this you can use whatever method you want and in the end parse the result with jsoup (if you really need it). Check this code :

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Main {  
    
        public static void main(String[] args) {
            try {
                String rawData = "RAW_DATA_HERE";
                String url = "URL_HERE";
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
                //add reuqest header
                con.setRequestMethod("METHOD_HERE"); //e.g POST
                con.setRequestProperty("KEY_HERE", "VALUE_HERE"); //e.g key = Accept, value = application/json
    
                con.setDoOutput(true);
    
                OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
    
                w.write(rawData);
                w.close();
    
                int responseCode = con.getResponseCode();
    
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
                String inputLine;
                StringBuffer response = new StringBuffer();
    
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
    
                in.close();
    
                System.out.println("Response code : " + responseCode);
                System.out.println(response.toString());
    
                //Use Jsoup on response to parse it if it makes your work easier.
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }