繁体   English   中英

Java 发送登录请求

[英]Java send post request for login

我想从 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、..)。 看看这里: 在 java 中发送 http 发布请求


也许您还必须设置 Content-Type:

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

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

我更喜欢 JSoup 的简单解决方案:

Document document  = Jsoup.connect("http://applicationURL/login.jsp")
        .data("email", "temail@mail.com")
        .data("password", "123password")
        .data("login", "login")
        .post();

HttpURLConnection 的默认方法是 GET。 您需要将其更改为 POST:

HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(HttpConnection.POST);

检查 commons-httpclient

这是帖子的示例: http://hc.apache.org/httpclient-3.x/methods/post.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM