-1

I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package). I'm using java.net.HttpURLConnection, here is a small region of my code :

URL obj = new URL(urlPost);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT

String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));

if (!typeRequest.equals("GET")){
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
        wr.writeBytes(postParam);
        wr.flush();
    }
}
if (con.getResponseCode() == 200){
    try (BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response += inputLine;
        }
    }
}

I tried sending my PUT parameters the "POST" way and also directly in the URL. It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.

Thanks for reading, I hope you will be able to give me some hints to debug the problem.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Icedsky
  • 13
  • 4

1 Answers1

0

What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122