我在Java中使用POST方法时遇到411 HTTP错误

时间:2017-01-07 09:47:54

标签: java rest url post

我现在在Java中使用POST方法时遇到了问题。我收到了

  

线程“main”中的异常java.lang.RuntimeException:服务器返回HTTP响应代码:411用于URL。

我无法在任何地方找到任何可用的文档。它们都没有用。我该如何解决?

我的代码

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

4 个答案:

答案 0 :(得分:2)

完美的工作方法:

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

如果您在回复中返回JSON:

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

答案 1 :(得分:0)

如果您仍然遇到麻烦,也许这会有所帮助。我没有测试,机器没有安装java。

您还应该设置所需的所有其他标题。

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 :(得分:0)

如果使用post方法,则应在正文中发送空数据。 例如,如果您使用的是json数据,则需要发送“ {}”

答案 3 :(得分:0)

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

    }