I am getting 411 HTTP Error while using POST method in Java

Question

I am facing a problem while using POST Method in Java nowadays. I am receiving

Exception in thread "main" java.lang.RuntimeException: Server returned HTTP response code: 411 for URL.

I couldn't find any available document anywhere. None of them were useful. How do I fix it?

My code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class req {
    public static void main(String[] args) {
        sendPostRequest(requestURL);
    }

    private static String sendPostRequest(String requestUrl) {
        StringBuilder jsonString = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            byte[] data = requestUrl.getBytes("UTF-8");


            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Content-Length", String.valueOf(data.length));
            connection.setRequestProperty("Authorization", "Basic " + "usename:password");

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                jsonString.append(line);
            }
            br.close();
            connection.disconnect();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return jsonString.toString();
    }
}

Show source
| url   | java   | rest   | post   2017-01-07 10:01 2 Answers

Answers ( 2 )

  1. 2017-01-07 12:01

    If you are still having trouble, maybe this will help. I did not test, machine does not have java installed.

    You should also set all other headers that you need.

    public static String PostRequest(String requestUrl, String username, String password) {
        StringBuilder jsonString = new StringBuilder();
        HttpURLConnection connection = null;
        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection)url.openConnection();
            byte[] authData = Base64.encode((username + password).getBytes());
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic " + new String(authData));
            connection.setRequestProperty("Content-Length", String.valueOf(authData.length));
            try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
                writer.writeBytes("REPLACE ME WITH DATA TO BE WRITTEN");
                writer.flush();
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String data = null;
                while ((data = reader.readLine()) != null) {
                    jsonString.append(data);
                }
            }
        } catch (IOException ex) {
            //Handle exception.
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        return jsonString.toString();
    }
    
  2. 2017-01-07 17:01

    Perfectly working method:

    public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
    
        URL url;
        String response = "";
        try {
            url = new URL(requestURL);
    
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
    
    
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
    
            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();
    
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                response = br.readLine();
            }
            else {
                response="Error Registering";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return response;
    }
    
    
    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
            StringBuilder result = new StringBuilder();
            boolean first = true;
            for(Map.Entry<String, String> entry : params.entrySet()){
                if (first)
                    first = false;
                else
                    result.append("&");
    
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
    
            return result.toString();
        }
    

    If you are returning a JSON in your response:

    public JSONObject getPostResult(String json){
        if(!json.isEmpty()) {
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON_ERROR", "Error parsing data " + e.toString());
            }
        }
        return jObj;
    }
    
◀ Go back