Java send post request for login

i want to login to application from java code.

I have found the following code example:

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

but i can not login, it returns back only login page.

If anybody can, please help me to understand what am i doing wrong.

I have added method and content-type, but it still does not work:

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

you didn't specify which method you're using (GET, POST, ..). have a look here: sending http post request in java


Maybe you also have to set your Content-Type:

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

Edit : Try to analyze the HTTP stuff using a browser with a socket sniffer (eg wireshark). There might be some special cases like, cookies or server side verification stuff you missed. Probably some hidden field which is being sent or something like that.. (it is a html form, right?)


The default method for an HttpURLConnection is GET. You need to change it to POST:

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

check commons-httpclient

this is example of post: http://hc.apache.org/httpclient-3.x/methods/post.html

链接地址: http://www.djcxy.com/p/45846.html

上一篇: java中的HTTP multipart类

下一篇: Java发送登录请求