How to send PUT, DELETE HTTP request in HttpURLConnection in JAVA

前端 未结 3 1246
[愿得一人]
[愿得一人] 2020-12-30 09:25

I have Restful WebServices, and i send POST and GET HTTP request, how to send PUT and DELTE request HTTP in httpURLConection with JAVA.

3条回答
  •  盖世英雄少女心
    2020-12-30 10:12

    PUT

    URL url = null;
    try {
       url = new URL("http://localhost:8080/putservice");
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    }
    HttpURLConnection httpURLConnection = null;
    DataOutputStream dataOutputStream = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestMethod("PUT");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        dataOutputStream.write("hello");
    } catch (IOException exception) {
        exception.printStackTrace();
    }  finally {
        if (dataOutputStream != null) {
            try {
                dataOutputStream.flush();
                dataOutputStream.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        if (httpsURLConnection != null) {
            httpsURLConnection.disconnect();
        }
    }
    

    DELETE

    URL url = null;
    try {
        url = new URL("http://localhost:8080/deleteservice");
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    }
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
        httpURLConnection.setRequestMethod("DELETE");
        System.out.println(httpURLConnection.getResponseCode());
    } catch (IOException exception) {
        exception.printStackTrace();
    } finally {         
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    } 
    

提交回复
热议问题