web-dev-qa-db-ja.com

JAVAのHttpURLConnectionでPUT、DELETEHTTPリクエストを送信する方法

Restful WebServicesがあり、Javaを使用したhttpURLConectionでPOSTおよびGETHTTPリクエスト、PUTおよびDELTEリクエストHTTPを送信する方法を送信します。

10
user2816207

プット

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();
    }
}

削除

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();
    }
} 
24
bmlynarczyk

@BartekMからのDELETEリクエストを使用すると、次の例外が発生します。

 Java.net.ProtocolException: DELETE does not support writing

これを修正するには、次の命令を削除します。

 // httpURLConnection.setDoOutput(true);

ソース: AndroidでHTTP DELETEリクエストを送信

5
spritus