java - java中的HTTP POST请求 - 设置内容长度

标签 java http-post

下面是我的代码,它执行 POST 请求来登录网站。当我运行相同的命令时,我收到的消息响应为 411。任何人都可以帮助我设置正确的内容长度吗?

  try {

        String request = "http://<domain.com>/login";

        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);

        connection.setInstanceFollowRedirects(false);
        connection.setRequestProperty("Content-Length", "1");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("email", "abc");
        connection.setRequestProperty("password", "xyz");

        connection.setDoOutput(true);

        connection.setRequestMethod("POST");

        int code = connection.getResponseCode();
        System.out.println("Response Code of the object is " +code);
        if(code == 200)
            System.out.println("OK");
        connection.disconnect();
        } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

最佳答案

好的 - 您没有将任何内容移动到请求正文中,因此您应该将长度设置为“0”。

添加:

连接.connect();

之后:

connection.setRequestMethod("POST");

google“httpurlconnection post 参数”,用于向 POST 请求添加参数。该网站至少有四五个解决方案。

关于java - java中的HTTP POST请求 - 设置内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26247555/

相关文章:

tomcat - Servlet 何时读取或写入实际数据

android - 将 xml 文件发送到 android 中的 Web 服务

java - 将文件保存到 Jersey API 中的服务器应用程序目录

Java JVM 选择和垃圾收集

java - JsonPath/ jackson : how to deserialize JSON array to a single Object ("[1,2,3]" -> Vector3d instance)?

java - 停止 C 进程时出现弹出窗口

java - 使用正则表达式解析 URL

java - 执行在 getOutputStream() 函数处自动停止 使用 servlet 推送通知

ios - 图片(或视频)在 Swift 中发布到服务器

Java POST HTTPsUrlConnection 返回 200 响应