Login to a website using httpURLConnection

Hello,
I would like to write a java program that connects to a website, logs in by sending relevant data to the javascript I copy-pasted below and then retrieves the information of the webpage reached after successful login.
<form action="/us/user.html" method="post" class="loginbg">
<script type="text/javascript">
// <![CDATA[
function makeFocus(el)
     switch(el.name)
          case "login_user":      if(el.value == 'Loginname')
                    el.value = '';
                    el.style.textAlign = 'left';
                    el.style.fontSize = '11px';
          break;
          case "login_pwd":      if(el.value == 'Password')
                    el.value = '';
                    el.style.textAlign = 'left';
                    el.style.fontSize = '11px';
                    el.type = "password";
          break;
function makeBlur(el)
     switch(el.name)
          case "login_user":      if(el.value == '')
               el.style.textAlign = 'center';
               el.style.fontSize = '9px';
               el.value = 'Loginname';
          break;
          case "login_pwd":      if(el.value == '')
               el.style.textAlign = 'center';
               el.style.fontSize = '9px';
               el.type = "text";
               el.value = 'Password';
          break;
// ]]>
</script>
<img src="design/user/login.png" alt="Login" title="Login" />
<input type="text" class="name" name="login_user" id="login_user" value="Loginname" onfocus="makeFocus(this);" onblur="makeBlur(this);" style="text-align:left; font-size:11px;" />
<input type="password" class="password" name="login_pwd" id="login_pwd" value="Password" onfocus="makeFocus(this);" onblur="makeBlur(this);" style="text-align:left; font-size:11px;" />
<a href="user,register.html"><img class="regist pngfix" src="design/user/button_regist.png" alt="Regisrieren" title="Registrieren" /></a>
<input class="submit" type="submit" name="send" value="Go!" />
</form>
<script type="text/javascript">
// <![CDATA[
if(document.getElementById('login_user'))
     var el = document.getElementById('login_user');
     if(el.value == 'Loginname')
          el.style.textAlign = 'center';
          el.style.fontSize = '9px';
     el = document.getElementById('login_pwd');
     if(el.value == 'Password')
          el.style.textAlign = 'center';
          el.style.fontSize = '9px';
          el.type = "text";
// ]]>
</script>
{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Read up on HTML and HTTP CGI subsection.
Basically, through the POST, the browser will send an HTTP Request with attached form data to http://[domain]/us/user.html.
All you need is that information and read the HTTP Response.
A typical POST to a server will look like this:
POST /someURL.html HTTP/1.1
Content-Type: text/plain
Content-Length: 68
username=testuser
password=letmein
hiddenfield1=loginform
...

Similar Messages

  • Login to a website using httpURLConnection and GET methods

    Hello,
    I would like to write a java program that connects to a website, logs in by sending relevant data to the javascript I copy-pasted below and then retrieves the information of the webpage reached after successful login.
    <FORM method="post" name="loginForm" action="/cvg/dispatch/login/submit">
    <TABLE>
    <TR>
    <TD>
    <TABLE BGCOLOR=#D0E2FF WIDTH="100%" BORDER="0" CELLPADDING="3" CELLSPACING="0">
    <TR><TD COLSPAN=2>�</TD></TR>
    <TR>
    <TD ALIGN="RIGHT"><FONT SIZE=3>login</FONT></TD>
    <TD><input type="text" name="loginValues.userName" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.userName"></TD>
    </TR>
    <TR>
    <TD ALIGN="RIGHT"><FONT SIZE=3>password</FONT></TD>
    <TD><input type="password" name="loginValues.password" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.password">
    </TD>
    </TR>
    <TR>
    <TD ALIGN="CENTER" COLSPAN=2>
    <input type="image" name="Login" value="Login" src="/cvg/images/login-button.gif" alt="Login" border="0" width="67" height="33" ><input type="hidden" name="submitButton" value="Login"><input type="hidden" name="Login-action" value="Login">
    </TD>
    </TR>
    </TABLE>
    Thanks for your help

    Using POST
    http://forum.java.sun.com/thread.jspa?threadID=645830
    second POST
    Using GET
    URL u = new URL("http://server/cvg/dispatch/login/submit?loginValues.userName=user&priority-normal=loginValues.userName&loginValues.passwor=password&priority...")
    By the way the html you provided does not use GET at all, it uses POST
    <FORM method="post" ring any bell?
    As for javascript, I don't see any script on the html page you provide, nor
    do I see any onsubmit or onclick action.

  • I was login a website ,and i have opened cookies , i want to open another window to login the same website use another account , and in the same windows can use the same account , how can i achieve it ? thinks

    i want to use firefox to login a website ,in the same window and different tags can user the same session
    but when i open other window and login the same website use different account .
    how can i achieve it ? thinks

    Your problem has nothing to do with the faults or limitations of a web browser.
    ''There can be only ONE active user logged in on a specific website during a whole Browsing Session. Even if you try to log-in using a new window it will sign-out the earlier User ID from that website. It will keep the most recent logged-in User ID active.''
    This is the general policy on which all websites are built. Even if you try to login the same website from another web browser, you won't be able to login from the second platform either. I just check it. Tried on Mozilla and Internet Explorer.

  • How can i login to a website using java

    hi,
    i tried to write a java program to which will take username and password and login to a given site. but some how its not working. i am actually trying to login to the follwoing website:
    https://roundup.ffmpeg.org/roundup/ffmpeg/
    can anyone provide some example program to login to this website.
    br
    mahbubul-syeed

    Hi,
    i am really sorry... but i am new in this forum and i did not know this. here is my code that i have written. it did not show any error and displays the content of the page but did not logged in. please give your comment.. i badly need a solution.
    package myUtility_files;
    import java.net.*;
    import java.io.*;
    public class LogInByHttpPost {
         //private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String LOGIN_ACTION_NAME = "submit";
    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "__login_name";
    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "__login_password";
    private static final String LOGIN_USER_NAME = "mahbubul";
    private static final String LOGIN_PASSWORD = "mahbubul007";
    private static final String TARGET_URL = "http://roundup.ffmpeg.org/roundup/ffmpeg/";
    public static void main (String args[])
    LogInByHttpPost httpUrlBasicAuthentication = new LogInByHttpPost();
    httpUrlBasicAuthentication.httpPostLogin();
    public void httpPostLogin ()
    try
    // Prepare the content to be written
    // throws UnsupportedEncodingException
    String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);
    HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
    //String response = readResponse(urlConnection);
    System.out.println("Successfully made the HTPP POST.");
    //System.out.println("Recevied response is: '/n" + response + "'");
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                   String inputLine;
                   while ((inputLine = in.readLine()) != null)
                        System.out.println(inputLine);
    catch(IOException ioException)
         ioException.printStackTrace();
    System.out.println("Problems encounterd.");
    private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
    // Encode the user name and password to UTF-8 encoding standard
    // throws UnsupportedEncodingException
    String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
    String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
    String content = "login=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
    + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
    return content;
    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
    HttpURLConnection urlConnection = null;
    DataOutputStream dataOutputStream = null;
    try
    // Open a connection to the target URL
    // throws IOException
    urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());
    // Specifying that we intend to use this connection for input
    urlConnection.setDoInput(true);
    // Specifying that we intend to use this connection for output
    urlConnection.setDoOutput(true);
    // Specifying the content type of our post
    //urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
    // Specifying the method of HTTP request which is POST
    // throws ProtocolException
    urlConnection.setRequestMethod("POST");
    // Prepare an output stream for writing data to the HTTP connection
    // throws IOException
    dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
    // throws IOException
    dataOutputStream.writeBytes(content);
    dataOutputStream.flush();
    dataOutputStream.close();
    return urlConnection;
    catch(IOException ioException)
    System.out.println("I/O problems while trying to do a HTTP post.");
    ioException.printStackTrace();
    // Good practice: clean up the connections and streams
    // to free up any resources if possible
    if (dataOutputStream != null)
    try
    dataOutputStream.close();
    catch(Throwable ignore)
    // Cannot do anything about problems while
    // trying to clean up. Just ignore
    if (urlConnection != null)
    urlConnection.disconnect();
    // throw the exception so that the caller is aware that
    // there was some problems
    throw ioException;
    br
    mahbubul-syeed
    Edited by: mahbubul-syeed on Jun 11, 2009 5:07 AM

  • I enter username and password to login into a website, use the site and then logoff. When I open the site again the username & password are alread filled in,

    The only way to prevent to from happening that I've found so far is to close Firefox. When I open back up, go to the site the username and password are empty. This hasn't happened with previous versions of Firefox.

    You can set the Boolean pref <b>signon.autofillForms</b> to <i>false</i> on the <b>about:config</b> page.
    *http://kb.mozillazine.org/signon.autofillForms
    *http://kb.mozillazine.org/about:config
    This can also be caused by cookies that weren't removed properly when you logged off.

  • How do i put a login in on my website using iweb

    I cant find anything on putting a login on my website so i can track users and see how many people are actually using my site and not just passing by.Can anyone tell me how i can do this? thanks!

    Page 36 in the Pages User Guide, downloadable from you Pages Help menu, has information on the issue. In the Inspector it looks like this

  • HT5559 JAVA WITH CHROME!!! I am trying to login to my bank account at nordea.dk. This website uses somekind of java thing. Chrome cant't load it. Works perfect with Safari. How to make it work in Chrome?

    I am trying to login to my bank account at nordea.dk. This website uses somekind of java thing. Chrome cant't load it. Works perfect with Safari. How to make it work in Chrome?

    Do you speak of true blue Java or Javascript?  If the latter then it is a problem with the Browser.
    But if it is the real Java, do you have the offical version of Java from Oracle installed?
    Getting applications to see official Java is a nightmare.  If you install the Runtime Environment only (JavaRTE) most applications do not see it.
    To force offical Java system wide, I found you have to install the Java Developer Kit (JavaJDK).  It's a larger install as it also comes with documentation and compilers but it make offical Java system wide.

  • Safari can use my CAC (Smart) Card to login to government websites but Firefox cannot.

    Safari and even Google Crome can access my CAC Card and login to government websites, however Firefox just doesn't seem to even try. OSX Lion, Apple Macbook Pro, Firefox 5.0.1.

    Try:
    * [/questions/808161] Trying to use a CAC smart card reader with Mac version of Firefox
    * https://militarycac.com/firefox.htm

  • I can't login on some websites, after I updated Firefox

    Hello.
    I'm running Firefox version 20.0.1, and I can't login on certain websites. The login details are corect, since I can login using Chrome. This started after the update to that latest version of Firefox. I haven't installed any new add-ons before the update, or after it.
    I cleared the cache (using Ccleaner and also from within browser's options), but that didn't solve my problem. I also cleared cookies, deleted browsing history, made sure I accepted 3rd party cookies. I also un-ticked the "I don't want to be tracked" option. I made sure that the sites I can't login into are not blocked from accepting cookies, or from anything else.
    I have some add-ons installed (Ad-block, HTTPS everywhere, etc.), which I disabled one-by-one to see if they were causing problems, but with no success. Since I could login before the update, it's clearly not an add-on problem here.
    Thank you.

    I deleted the cookies.sqlite, but I still cannot' login into those sites.

  • Using HttpUrlConnection

    Hi ,
    I'm facing problem in Using HttpUrlConnection. When I submit a request to sun java web server 1.6 . By using the following code I request the server , The server receives the request but can not read the request body that is written on the connection output stream.
    my client code :
    URL page = new URL(url);
    HttpURLConnection sock = (HttpURLConnection) page.openConnection();
    sock.setRequestMethod("POST");
    sock.setRequestProperty("Content-Length",
    "" + Integer.toString(body.getBytes().length));
    sock.setUseCaches(false);
    sock.setDoOutput(true);
    if (body.length() > 0) {
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeBytes(body);
    out.flush();
    out.close();
    sock.connect();
    BufferedReader in = new BufferedReader (new InputStreamReader(sock.getInputStream(),"Cp1256"));
    int nHttpResponseCode = sock.getResponseCode();
    if(nHttpResponseCode != HttpURLConnection.HTTP_OK){
    System.out.println("\tHttp error:" + nHttpResponseCode );
    in.close();
    return nHttpResponseCode;
    //receive reply
    in.close();
    return nHttpResponseCode;
    My server code is :
    String params = null;
    try {
    java.io.InputStream in = request.getInputStream();
    byte b[] = new byte[1000]; //in.available()];
    in.read(b);
    char[] s = new char[b.length];
    for (int i = 0; i < b.length; i++) {
    if (b[i] == 0)break;
    s= (char) b[i];
    params = new String(s);
    catch (Exception exp) {
    exp.printStackTrace();
    I tried to submit the request after appending the request body to the url (url like that http://ipadd/webapp/page.jsp?appndedVlaues) and retreived the appended string by calling getQueryString method and It worked well.
    Does anybody faced such a problem before?
    please help
    Thanks

    I have done things like this several times with the URLConnection class and it always seem to work. I do not, however, call the
    sock.connect();
    method. My code seems to work fine without it. First I get the OutputStream and write to it. Then I get the InputStream and read the data from it.
    Does the "body" variable in the client code contain any data at all? I don't see it initialized anywhere with data.
    I have recently developed a file upload component. It's open source, Apache License and available from our website, www . jenkov . com. It works fine, and that too reads data from the request.getInputStream(). Perhaps you can look at that code and see if you can steal some bits that can make your server code work?

  • Why can't I login to some websites since iOS 7 upgrade?

    I can't login to a website from my iPad although the same login details work fine when logging in from my PC. This has started happening since the upgrade to iOS 7. Can anyone suggest why and what I can do to resolve this, please? Thanks for any advice.

    It seems this is was not an iOS 7 problem after all. I was just using the wrong password! D'oh! The password field is pre-filled on my PC but not on the iPad. In my defence the error message I was getting said my email address didn't match their records. However I should have checked by typing the password in on my PC, which is what I eventually did.
    After having so many problems with iOS 7 I guess i'm starting to jump to the conclusion that it is to blame for everything!
    Sorry for wasting everyone's time.
    *wears dunces hat*

  • 1Password doesn't auto-fill logins on some websites

    Using iMac, OS X 10.6.8, 1Password 3.8.1
    1Password will not auto-fill logins for some websites. E.g., VISA & my bank sites.
    Thanks!

    Hello Mike:
    Some web sites deliberately prohibit auto-filling of fields. This is normally for security reasons (banks, credit cards). There is nothing that I am aware of that you can do to override the coding on those sites.
    Barry

  • Safari crashes when a website uses kerberos credentials

    has anyone successfully used Safari to successfully login to a website which utilizes kerberos authentication? This worked fine under Tiger, but it completely crashes Safari in Leopard.

    This looks like it was resolved in the 10.5.1 update.

  • Trying to Access Website using SSL running JAVA from inside ORACLE DB

    Hi,
    I am trying to access website using SSL and running JAVA code from inside Oracle 10g DB server using SSL and Java. I have loaded my java code into Oracle data base. My problem is when I am running same code from outside the DB it is running perfectly fine but when the same code is loaded into DB and trying to run from DB under these environment I am using for running my code:-
    JDK 1.4.2_06
    JSSE 1.4
    Database :- Oracke 10G
    I am getting following Exception:-
    CALL testssl_http_mar20_New();
    java.io.IOException: Unable to tunnel through 123.456.789.123:80. Proxy returns "HTTP/1.1 407 Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied.)
    at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a(DashoA12275
    at
    com.sun.net.ssl.internal.www.protocol.https.HttpsClient.doConnect(DashoA12275)
    at
    com.sun.net.ssl.internal.www.protocol.https.NetworkClient.openServer(DashoA12275
    at com.sun.net.ssl.internal.www.protocol.https.HttpClient.l(DashoA12275)
    at com.sun.net.ssl.internal.www.protocol.https.HttpClient.<init>(DashoA1
    2275)
    at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.<init>(DashoA
    12275)
    at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a(DashoA12275
    at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a(DashoA12275
    at
    com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.connect(DashoA122
    75)
    at
    com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.getInputStream(Da
    shoA12275)
    at java.net.URL.openStream(URL.java:924)
    at SecureURLhttp_Mar20_New.SecureURLhttp_Mar20_New(
    source code is below :-
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.util.*;
        public class SecureURLhttp
              public static void main(String[] args) throws Exception
                  SecureURLhttp r = new SecureURLhttp();
                  r.SecureURLhttp();
        public static void SecureURLhttp() throws IOException
                System.setProperty("java.protocol.handler.pkgs","oracle.aurora.rdbms.url|com.sun.net.ssl.internal.www.protocol");
                System.setProperty("https.proxySet","true");
                Authenticator.setDefault(new MyAuthenticator());
                System.setProperty("https.proxyHost","123.456.789.123");
                System.setProperty("https.proxyPort","80");
               //  URL verisign = new URL("https://login.oracle.com/");
                URL verisign = new URL("https://www.verisign.com");
                BufferedReader in = new BufferedReader(new InputStreamReader(verisign.openStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
                in.close();
                 /* Code Newly Add for checking the system property   */
                java.util.Properties props = System.getProperties();
                java.util.Enumeration propNames = props.propertyNames();
                 while (propNames.hasMoreElements ())
                 Object o=  propNames.nextElement();
                 String name = (String ) o;
                 String val =  props.getProperty(name)   ;
                 System.out.println ( name +  "  = "  + val );
        private static class MyAuthenticator extends Authenticator {
              protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication("<USERNAME>",new String("<USER_PASSWORD>").toCharArray());
         }Please help me out:
    Thanks a lot in advance.

    0- the fact the ISA server logs an 'anonymous' seems logical, since it answers by HTTP 407. I will say it's even a "good log" :) but I had preferred a good old "security exception" but it's not the case..
    1- The code for checking the properties (your debugging) should be placed BEFORE trying to connect to the url if you want to see what's happening
    2- The 'normal' way to set the proxy is to set the following properties
    System.setProperty("http.proxySet","true"); // and NOT https.proxyset as ejp said
    System.setProperty("http.proxyHost","123.456.789.123");
    System.setProperty("http.proxyPort","80");
    3- what's the behavior if you change 123.456.789.123 by the real name (hostname) of the server ?
    4- You can try setting up the proxy in the java control panel instead of in your code (easy to do under Windows, you look for the networking settings, and you find the proxy settings for http/https there. Otherwise look for all files called net.properties and edit them).
    5- to help debbuging, we can rely on several methods of Authenticator :
    protected PasswordAuthentication getPasswordAuthentication() {
    System.err.println(".\tgetRequestingHost: " + getRequestingHost());
    System.err.println("..\tgetRequestingSite: " + getRequestingSite());
    System.err.println("...\tgetRequestingPort: " + getRequestingPort());
    System.err.println("....\tgetRequestingProtocol: " + getRequestingProtocol());
    System.err.println(".....\tgetRequestingPrompt: " + getRequestingPrompt());
    System.err.println("......\tgetRequestingScheme: " + getRequestingScheme());
    return new PasswordAuthentication("<USERNAME>",new String("<USER_PASSWORD>").toCharArray());
    Try all this and let us see the output messages.
    Please remember to give some 'duke stars' if it helped resolving the problem ;)
    NephYliM

  • Logging in on website using java

    Hello,
    I am quite inexperienced when it comes to java programming, so my apologies if I post this in the wrong section.
    I am trying to open a website using java. So far I succeeded in reading the source code through java, which is about halfway I want to get. However, for getting the information I want, I need to login on the website with my account. I have no idea how something like that should be done. Cookies are used to login, and I am using BlueJ for my program. Could anyone help me out with an example or explanation on how this is done?
    Thanks in advance,
    Tybs

    I downloaded the httpclient tool, it looks promising. I managed to open it in blueJ, so far so good... the only problem now is that I can't compile it. Each class gives me an error message. This one, for example:
    import test.com.meterware.httpunit.*;
    package test.com.meterware.httpunit does not exist
    I found the necessary packages in the tool itself, but I have no idea how I can specify the path to them, or how I can add them to the packages that java already has. What do I need to do for this?
    Thanks for the information so far, it really helps :D
    Greetz,
    Tybs

Maybe you are looking for

  • What are the consequences of De-Authorizing all computers.

    I've had an iTunes account for years and its only fairly recently that i've been a bit more aware of the authorizing of computers. I've hit my limit of 5 but 3 of these are computers that i no longer own and don't have access to. I have made purchase

  • IdeaCentre B320 black screen

    My Ideacentre B320 gets a black screen on startup but I can hear Windows starting normally and when I try the TV I only get the Lenovo logo screen and nothing else. I found a post from someone with the exact same problem but with a B340. It turned ou

  • OBPM SUITE DOWNLOAD

    Hi, As i know that OBPM SUITE has 5 intergrated tools 1)ORACLE BUSINESS PROCESS MANAGEMENT 2)ORACLE BPEL PROCESS MANAGER 3)ORACLE BUSINESS ACTIVITY MONITORING 4)ORACLE BUSINESS RULES 5)ORACLE WEBCENTER SUITE Is there any option to downlaod 5 tools wh

  • [solved] how to easy encrypt HOME\USER folder?

    Hi Amigos! Can somone give me easy step by step guide how to easy encrypt home directory in Linux Arch please? I spent all day to try encrypt home directory (how I did it before in Debian) I used encyptfs-migrate-home -u [myusername] but after all en

  • Auto-stack bracketed raw images?

    When I execute the auto-stack panorama / HDR command on a directory filled with exposure bracket groups intended for HDR processing, Bridge issues a warning message "Image is missing preview data" apparently for each and every image it inspects.  If