nuhkoca
nuhkoca

Reputation: 1943

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

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

Upvotes: 1

Views: 11906

Answers (4)

shailesh kashyap
shailesh kashyap

Reputation: 1

public void Post() throws Exception {
 StringBuffer d = new StringBuffer();
        String da = "ClearanceDate=2020-08-31&DepositeDate=2020-08-31&BankTransactionNo=UATRYU56789";
        URL url = new URL("https://abcd/AddReceipt?" + da);
        byte[] postDataBytes = ("https://abcd/AddReceipt?" + da).toString()
                .getBytes("UTF-8");
        System.out.println("Data--" + postDataBytes);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        // con.setRequestProperty("User-Agent",
        // "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length",
                String.valueOf(postDataBytes.length));
        con.setRequestProperty(
                "Authorization",
                "Bearer "
                        + "o731WGgp1d913ZOYivnc55yOg0y1Wk7GsT_mnCUKOJf1VChYOdfRjovAxOhyyPKU93ERue6-l9DyG3IP29ObsCNTFr4lGZOcYAaR96ZudKgWif1UuSfVx4AlATiOs9shQsGgb1oXN_w0NRJKvYqD0LLsZLstBAzP1s5PZoaS9c6MmO32AV47FUvxRT6Tflus5DBDHji3N4f1AM0dShbzmjkBCzXmGzEDnU6Jg1Mo5kb884kParngKADG5umtuGbNzChQpMw_A0SyEYaUNh18pXVmnNhqM3Qx5ZINwDEXlYY");
        con.setRequestProperty("Accept", "application/json");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.getOutputStream().write(postDataBytes);
        int status = con.getResponseCode();
        System.out.println("Response status: " + status + "|"
                + con.getResponseMessage());
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        con.disconnect();
        System.out.println("Response status: " + status);
        System.out.println(content.toString());
        System.out.print("Raw Response->>" + d);

    }

Upvotes: 0

Seda Budayoğlu
Seda Budayoğlu

Reputation: 1

You should send empty data in body if you are using post method. For example if you are using json data you need to send "{}"

Upvotes: 0

Pranjal Choladhara
Pranjal Choladhara

Reputation: 915

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

Upvotes: 2

Dillon
Dillon

Reputation: 106

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

Upvotes: 0

Related Questions