Java发送post登录请求

标签 java http post authentication

我想从 java 代码登录到应用程序。

我找到了以下代码示例:

 String requestURL = "http://applicationURL/login.jsp"; 
 String data = "email=temail@mail.com&password=123password&login=Login";


 public static String sendPostRequest(String data, String requestURL) {

         String result="";
        try {

            // Send the request
            URL url = new URL(requestURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

            //write parameters
            writer.write(data);
            writer.flush();

            // Get the response
            StringBuffer answer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            writer.close();
            reader.close();

            //Output the response
            System.out.println(answer.toString());
            result = answer.toString();

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
         return result;
    }

但我无法登录,它只返回登录页面。

如果有人可以,请帮助我理解我做错了什么。

我已经添加了方法和内容类型,但它仍然不起作用:

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

最佳答案

您没有指定您使用的是哪种方法(GET、POST、..)。看看这里:sending http post request in java


也许你还需要设置你的内容类型:

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

编辑:尝试使用带有套接字嗅探器(例如 wireshark)的浏览器来分析 HTTP 内容。可能有一些特殊情况,例如您错过的 cookie 或服务器端验证内容。可能是一些正在发送的隐藏字段或类似的东西..(它是一个 html 表单,对吧?)

关于Java发送post登录请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6544339/

相关文章:

java - 客户端休息 SSL java : javax.net.ssl.SSLHandshakeException

java - Spring Security ACL - 具有 READ 权限的用户可以撤销自己的访问权限吗?

java - 查找定期重复出现的时间间隔是否相互重叠的算法?

使用 libcurl 更改内容类型

http - 服务器端Dart中的跨域请求

javascript - 使用 Mongoose 处理六个文档后,我得到 "Failed to load resource: net::ERR_EMPTY_RESPONSE"

javascript - 无法使用ajax将文件发送到php文件

java - 如何通过其uid获取Firestore用户列表?

java - 发布请求。安卓

java - 请求不适用于 HttpURLConnection 但适用于其他 HTTP 客户端