Differences of URLConnection,HttpURLConnection,HttpsURLConnection

I find that all of them can connect to HTTPS,but what are differences of them when them are used to connected to HTTPS
Any help is appreciated.
Thanks in advance.

Thanks a lot.
But
If URL="https://www.sun.com",
URLConnection con;
HttpURLConnection httpcon;
HttpsURLConnection httpscon;
con=URL.openConnection
httpcon=(HttpURLConnection)URL.openConnection
httpscon=(HttpsURLConnection)URL.openConnection
what are the differences of con,httpcon,httpscon?
All of them can get infomation from the URL based HTTPS protocol.

Similar Messages

  • JSP with URLConnection or HttpsURLConnection, please help!

    Thanks in advance for looking at this post :)
    I have to develop an application. This application consists of a JSP form that collects credit card information. The form using a java bean to validate user input.
    Once the input has been validated I need to connect to a URL and transmit this collected data and receive a response from the remote server. My questions are:
    1. My plan of action is to write the java code required to connect to the URL and transmit the data within that java bean itself. Is this an acceptable way to handle it? OR should I make a separate bean for this, OR should I embed the code directly into the JSP?
    2. My server is set up with a secure certificate. I need to connect to URL using the https protocol. Do I use URLConnection or HttpsURLConnection? I already wrote the code using URLConnection, and I can connect and receive a response from the server. However the test I ran is just a system check (still connecting to https://). I am concerned about the security of data being transmitted via a URL Connection (obviously need to make sure this is encrypted going out as well as coming in since it will contain credit card info).
    I appreciate the response, I need to get this figured out asap.
    Thanks!

    By the way thanks for your input - sorry for the delay with the dukes... I got URLConnection working and from what I can tell all is good. Now posting to set a timeout feature on URLConnection:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=386270

  • URL,URLConnection,HttpURLConnection &&Session

    Hi,all
    I want to access a web page by URL/URLConnection/HttpURLConnection
    the page need a login user,it check the Session,if the session is null,then it redirect to the login page
    Now I have the user ID and Password ,and I can complete my login by URL Class
    but when I access the wanted page after I login,it's still return that the session is not set.
    below is the Code Segment,thanx in advance
    String urlStr = "http://buyc:8080/ecommerce/oa/login.jsp?txtUsername=sh001&txtPwd=111111&role=storeman";
    URL url = new URL(urlStr);
    HttpURLConnection hurlc =(HttpURLConnection) url.openConnection();
    hurlc.setFollowRedirects(true);
    hurlc.setInstanceFollowRedirects(true);
    hurlc.setUseCaches(true);
    hurlc.connect();//if check login successfully in login.jsp,it will redirect to a check page.
    InputStream is=hurlc.getInputStream();//
    byte tmpbyte[]=new byte[is.available()];
    int num=is.read(tmpbyte);
    String result=new String(tmpbyte);
    System.out.println("the " + num + ":" + result);

    IIRC, you use the UrlConnection's methods getHeaderField and getHeaderFields to get the cookies, and then setRequestProperty to set the cookies on subsequent connections. These methods are inherited by HttpUrlConnection.
    There may be a library out there to make this stuff easier, but I don't think it's in the standard libraries.

  • Setting Timeout  in URLConnection/HttpURLConnection

    Hi all,
    I am trying to open a connection a website using the java.net.HttpURLConnection.
    Please tell me what is the default timeout (how much time it will wait for getting reply ) and how we can change the
    default value. Please help me.
    Thanks in advance.

    This seems to be what you are looking for.
    [http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29|http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29]

  • HTTPSURLConnection/JSSE

    Hi...I am having some difficulty making a secure connection to send/receive streams. In order to connect to non-secure sites, I use the following code:
    // Initialize URL variables
    URL url = null;
    HttpURLConnection urlConnection = null;
    // Get handle to URL and its connection
    url = new URL("http://www.whatever.com");      
    urlConnection = (HttpURLConnection)url.openConnection();
    // Open input/output stream
    [Add code to open stream(s) here]      
    // Clean up
    [Add code to close stream(s) here]
    This code works fine. When I change the URL to a "HTTPS" URL, the code throws a malformed URL exception. I understand that this is because the HTTPS protocol is not understood and JSSE must be used. So, I installed JSSE in the appropriate directory, added the JAR files to my class path, and changed the above code to this:
    // Initialize URL variables
    URL url = null;
    HttpsURLConnection urlConnection = null;
    // Add provider
    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    // Get handle to URL and its connection
    url = new URL("https://www.whatever.com");      
    urlConnection = (HttpsURLConnection)url.openConnection();
    // Open input/output stream
    [Add code to open stream(s) here]      
    // Clean up
    [Add code to close stream(s) here]
    Unfortunately, the code blows up when I try to open an input or output stream. I get the following in the log:
    java.net.SocketException: SSL implementation not available at javax.net.ssl.DefaultSSLSocketFactory.createSocket([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.doConnect([DashoPro-V1.2-120198])     at com.sun.net.ssl.internal.www.protocol.https.NetworkClient.openServer([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpClient.l([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpClient.<init>([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.<init>([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a([DashoPro-V1.2-120198])      at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a([DashoPro-V1.2-120198])      at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.connect([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.getInputStream([DashoPro-V1.2-120198])
         at https_test.executeTest(https_test.java:91)
         at https_test.service(https_test.java:133)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1416) at allaire.jrun.session.JRunSessionService.service(../session/JRunSessionService.java:1082)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:1270) at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:89)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1552) at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1542)
         at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:364)
         at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:115)
         at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
         at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)
    java.net.SocketException: SSL implementation not available     at javax.net.ssl.DefaultSSLSocketFactory.createSocket([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.doConnect([DashoPro-V1.2-120198])     at com.sun.net.ssl.internal.www.protocol.https.NetworkClient.openServer([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpClient.l([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpClient.<init>([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.<init>([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a([DashoPro-V1.2-120198])     at com.sun.net.ssl.internal.www.protocol.https.HttpsClient.a([DashoPro-V1.2-120198])     at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.connect([DashoPro-V1.2-120198]) at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnection.getInputStream([DashoPro-V1.2-120198])
         at https_test.executeTest(https_test.java:93)
         at https_test.service(https_test.java:135)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1416) at allaire.jrun.session.JRunSessionService.service(../session/JRunSessionService.java:1082)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:1270) at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:89)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1552)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1542)
         at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:364)
         at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:115)
         at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
         at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)
    I have tried both static and dynamic registration, and both at the same time! For static registration, I do the following:
    1. Copied the 3 JSSE JAR files to $JREHOME/lib/ext
    2. Modified the java.security file to add the additional security provider
    For dymaic registration, I do the following:
    1. Added the 3 JAR files to my classpath
    2. Added a line (shown in code above) to dynamically add the provider
    I feel like I have done everything but it still does not work! Any help would be greatly appreciated. Thanks!!

    In what order did you put the security provider in when you modified the java.security file. I added it as the second provider in the list, only behind the original default provider and it eliminated that error
    //original default provider
    security.provider.1=sun.security.provider.Sun
    //provider necessary for SSL com
    security.provider.2=com.sun.net.ssl.internal.ssl.Provider

  • InputStream in = urlconnection.getInputStream();

    Dear All,
    I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
    In the client program, after opening all the necessary streams and all formalities, i am using the code...
    "InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1);"
    only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
    so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
    what to do???
    any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
    sakthivel s.
    snippet code for ur reference...
    Client side
    try
    ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
    ZipEntry zipentry = new ZipEntry(filename);
    zipentry.setMethod(ZipEntry.DEFLATED);
    zipoutputstream.putNextEntry(zipentry);
    byte bytearray[] = new byte[1024];
    File file = new File(filenamedir);
    FileInputStream fileinputstream = new FileInputStream(file);
    BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
    int length = 0;
    while((length=bufferedinputstream.read(bytearray)) != -1)
    zipoutputstream.write(bytearray,0,length);
    fileinputstream.close();
    bufferedinputstream.close();
    zipoutputstream.flush();
    zipoutputstream.finish();
    zipoutputstream.closeEntry();
    zipoutputstream.close();
    InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1); // the said while loop....................
    System.runFinalization();
    urlconnection.getInputStream().close();
    urlconnection.disconnect();
    the way of connecting witht the server : (just a snippet of the code)
    URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
    HttpURLConnection.setFollowRedirects(true);
    urlconnection= (HttpURLConnection)serverURL.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setRequestMethod("POST");
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    urlconnection.setUseCaches(false);
    urlconnection.setAllowUserInteraction(true);
    urlconnection.setRequestProperty("Cookie",cookie);
    urlconnection.connect();
    Server Side:
    javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
    ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
    ZipEntry zipentry = null;
    String directory="c:\\test"; // the unzipped file should be written to this directory...
    try
    File file = new File(directory);
    if(!file.exists())
    file.mkdirs();
    catch(Exception exp)
    {System.out.println("I am from Server: " + exp);}
    try
    zipentry = zipinputstream.getNextEntry();
    if(zipentry != null)
    int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
    String filename = zipentry.getName().substring(slash);
    File file1 = new File(directory + File.separator + filename);
    FileOutputStream fostream = new FileOutputStream(file1);
    BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
    byte abyte0[] = new byte[1024];
    for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
    bufferedoutputstream.write(abyte0, 0, index);
    servletinputstream.close();
    bufferedoutputstream.flush();
    bufferedoutputstream.close();
    zipinputstream.closeEntry();
    zipinputstream.close();
    fostream.flush();
    fostream.close();
    catch(IOException ioexception)
    {System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
    P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

    snoopybad77 wrote:
    I can't, I'm using java.net.URL and java.net.URLConnection....Actually you are using HttpURLConnection.
    java.net.URLConnection is an abstract class. The concrete implementation returned by openConnection for an HTTP based URL is HttpURLConnection. So you might want to try the previous suggestion and otherwise examining the methods of HttpURLConnection to see how they might be helpful to you.

  • How can we close a URLConnection ?

    Problem: URL Connections sometimes hang if, socket is there but not responding... the code will hang at urlConnection.getHeaderField(i).
    and My code will keep waiting for infinity ... only solution I have is to close the connection after a specified time (Using a thread).
    Sadly java.net.URLConnection doesn't have close() ...
    Can someone help me on this?
    Regards,
    Neo
    * HostExaminer.java
    * Created on September 28, 2002, 9:47 PM
    package serverconfig.microkernel.examiner;
    import java.net.Authenticator;
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.InputStream;
    import java.util.StringTokenizer;
    import serverconfig.microkernel.request.Request;
    import serverconfig.microkernel.worker.Director;
    import serverconfig.microkernel.worker.Locator;
    import serverconfig.microkernel.worker.Guardian;
    import serverconfig.microkernel.examiner.PresentationObjectInputStream;
    * @author  Neo
    public class HostExaminer implements Examiner {
        /** Creates a new instance of HostExaminer */
        public HostExaminer() {
        public boolean examine(final Request request, PresentationObjectInputStream presentationObjectInputStream){
            Guardian guardian = null;
            synchronized(guardian = Guardian.getInstance(request)){
                Authenticator.setDefault(guardian);
                try{
                    System.out.println("Before URL");
                    final URL url = new URL(new Locator(request).getInstanceURL()+new Director(request).getDirection());
                    System.out.println("Before URLConnection");
                    URLConnection urlConnection = url.openConnection();
                    System.out.println("Before for(;;)");
                    for(int i=0 ; ; i++){
                        System.out.println("Before urlConnection.getHeaderField("+i+");");
                        String header = urlConnection.getHeaderField(i);// <-- here it hangs
                        if(header == null ) break;
                        System.out.println("Before urlConnection.getHeaderFieldKey("+i+");");
                        final String headerKey = urlConnection.getHeaderFieldKey(i);
                        if(headerKey == null){
                            final StringTokenizer stringTokenizer = new StringTokenizer(header," ");
                            stringTokenizer.nextToken();
                            final String token = stringTokenizer.nextToken();
                            request.getResponse().setCode(new Integer(token.trim()));
                        //request.getResponse().appendContent( (headerKey == null ?"": (headerKey + " = ")) + header +"\n" );
                    System.out.println("Before presentationObjectInputStream");
                    presentationObjectInputStream.setInputStream(urlConnection.getInputStream());
                catch(java.net.UnknownHostException uhe){
                    request.getResponse().setCode(new Integer(404));
                    uhe.printStackTrace();
                    return false;
                catch(java.net.ProtocolException pe){
                    request.getResponse().setCode(new Integer(401));
                    pe.printStackTrace();
                    return false;
                catch(java.net.BindException be){
                    request.getResponse().setCode(new Integer(401));
                    be.printStackTrace();
                    return false;
                catch(java.net.ConnectException ce){
                    request.getResponse().setCode(new Integer(503));
                    ce.printStackTrace();
                    return false;
                catch(java.net.NoRouteToHostException nrthe){
                    request.getResponse().setCode(new Integer(408));
                    nrthe.printStackTrace();
                    return false;
                catch(java.io.IOException io){
                    request.getResponse().setCode(new Integer(500));
                    io.printStackTrace();
                    return false;
                catch(java.lang.Throwable th){
                    request.getResponse().setCode(new Integer(500));
                    th.printStackTrace();
                    return false;
            if(request.getResponse().getCode().intValue() >= 400){
                return false;
            else{
                return true;
    }

    HttpURLConnection.disconnect()
    *Sun's Comment:
    * Indicates that other requests to the server are unlikely in the near future.
    * Calling disconnect() should not imply that this HttpURLConnection instance can be reused for other requests.
    public abstract void disconnect(){
    Can you please make me under `what does this comment mean ?`
    Thanx Hedin, HttpURLConnection makes my code neat :) but this method does not close the connection!
    Regards,
    Neo
    * HostExaminer.java
    * Created on September 28, 2002, 9:47 PM
    package serverconfig.microkernel.examiner;
    import java.net.HttpURLConnection;
    import java.net.Authenticator;
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.InputStream;
    import java.util.StringTokenizer;
    import serverconfig.microkernel.request.Request;
    import serverconfig.microkernel.worker.Director;
    import serverconfig.microkernel.worker.Locator;
    import serverconfig.microkernel.worker.Guardian;
    import serverconfig.microkernel.examiner.PresentationObjectInputStream;
    * @author  Neo
    public class HostExaminer implements Examiner {
        HttpURLConnection urlConnection;
        /** Creates a new instance of HostExaminer */
        public HostExaminer() {
        public void disconnect(){
            if(urlConnection != null)
                urlConnection.disconnect();
        public boolean examine(final Request request, PresentationObjectInputStream presentationObjectInputStream){
            Guardian guardian = null;
            synchronized(guardian = Guardian.getInstance(request)){
                Authenticator.setDefault(guardian);
                try{
                    System.out.println("Before URL");
                    final URL url = new URL(new Locator(request).getInstanceURL()+new Director(request).getDirection());
                    System.out.println("Before URLConnection");
                    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                    System.out.println("Before get Response Code");
                    request.getResponse().setCode(new Integer(urlConnection.getResponseCode())); //<<-- It hangs here now !
                    System.out.println("Before presentationObjectInputStream");
                    presentationObjectInputStream.setInputStream(urlConnection.getInputStream());
                catch(java.net.UnknownHostException uhe){
                    request.getResponse().setCode(new Integer(404));
                    uhe.printStackTrace();
                    return false;
                catch(java.net.ProtocolException pe){
                    request.getResponse().setCode(new Integer(401));
                    pe.printStackTrace();
                    return false;
                catch(java.net.BindException be){
                    request.getResponse().setCode(new Integer(401));
                    be.printStackTrace();
                    return false;
                catch(java.net.ConnectException ce){
                    request.getResponse().setCode(new Integer(503));
                    ce.printStackTrace();
                    return false;
                catch(java.net.NoRouteToHostException nrthe){
                    request.getResponse().setCode(new Integer(408));
                    nrthe.printStackTrace();
                    return false;
                catch(java.io.IOException io){
                    request.getResponse().setCode(new Integer(500));
                    io.printStackTrace();
                    return false;
                catch(java.lang.Throwable th){
                    request.getResponse().setCode(new Integer(500));
                    th.printStackTrace();
                    return false;
            if(request.getResponse().getCode().intValue() >= 400){
                return false;
            else{
                return true;

  • Need some help in HttpURLConnection

    Hi,
    I am having trouble with the HttpURLConnection and hope someone could help me with this. I have the following code, which reads lines of data from a file and each time a line is read, I want to send the data across to a servlet.
    String urlString = "http://leewse:8080/vms/tracking.srv";
              try {
                   URL url = new URL(urlString);
                   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                   conn.setRequestMethod("GET");
              conn.setUseCaches(false);
              conn.setDoInput(true);
              conn.setDoOutput(true);
                   DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                   String dataString, line, coordinates, vehicleNumber;
              StringTokenizer stringTokenizer;
                   BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\vms_simulator\\location.txt"));
                   while ((line = bufferedReader.readLine()) != null) {
                   stringTokenizer = new StringTokenizer(line, ";");
                   coordinates = stringTokenizer.nextToken();                    
                   vehicleNumber = stringTokenizer.nextToken();               
                        out.writeBytes("vehicleNumber=" + URLEncoder.encode(vehicleNumber, "UTF-8") +
                        "&from=" + URLEncoder.encode("list", "UTF-8") +
                             "&method=" + URLEncoder.encode("edit", "UTF-8") +
                        "&coordinates=" + URLEncoder.encode(coordinates, "UTF-8"));
                   out.flush();
                   //out.close();
                   System.out.println(conn.getContentType());
                   System.out.println(conn.getResponseMessage());      
                   conn.disconnect();     
              catch (MalformedURLException e) {
                   e.printStackTrace();
              catch (IOException e) {
                   e.printStackTrace();
    However, I observed that only the first line of data is successfully sent over to the servlet, while subsquent lines of data are not. Could someone please kindly point out where I went wrong? Thanks.

    I have figured out what is causing the "Exception in thread "main" java.lang.NoClassDefFoundError". Apparently, HttpClient requires the commons logging in order to work.
    In any case, I have this code:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    public class Simulator {
      public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        PostMethod httppost = new PostMethod("http://leewse:8080/vms/tracking.srv");
        httppost.setContentChunked(true);
        String line, vehicleNumber, coordinates;
        StringTokenizer stringTokenizer;
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\vms_simulator\\location.txt"));          
        while ((line = bufferedReader.readLine()) != null) {
              stringTokenizer = new StringTokenizer(line, ";");
              coordinates = stringTokenizer.nextToken();                    
              vehicleNumber = stringTokenizer.nextToken();               
              httppost.setParameter("vehicleNumber", vehicleNumber);
              httppost.setParameter("coordinates", coordinates);
              try {
                   client.executeMethod(httppost);
                   if (httppost.getStatusCode() == HttpStatus.SC_OK)
                        System.out.println(httppost.getResponseBodyAsString());
                   else
                        System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
              finally {
                   httppost.releaseConnection();
    }In any case, here are two things about this code:
    1. It can now talk to the servlet for more than once, but the problem is, the parameters cannot be retrieved at the servlet, meaning req.getParameter() always return null. What could be the reason for this?
    2. It also causes a lot of sessions to be created, just like HttpURLConnection. So it seems like it makes no difference to use HttpURLConnection or HttpClient when it comes to resolving my concern? Are HttpURLConnection and HttpClient built on the concept of "one-session-one-request-only"?

  • URLConnection error on https

    Hello,
    i have noticed an error, that makes sometimes troubles, when downloading jars from https addresses, when there are many jars to download..
    Best example is by opening Javas onw Java version checker.
    https://www.java.com/en/download/installed.jsp
    I get also following log...
    network: Connecting https://www.java.com/jsp_utils/jreverification.jar with proxy=DIRECT
    network: Connecting http://www.java.com:443/ with proxy=DIRECT
    network: Connecting https://www.java.com/jsp_utils/jreverification.jar with cookie "JSESSIONID=22ABBA2BE9B5789629C276AC35BDF969; s_cc=true;
    Even if the address is https, java try to access via http protocol on port 443, and that leads sometimes to problems..
    I have noticed this, when I have used URLConnection(HttpURLConnection) for my self, as soon Java sends http link on https address, the jar gets sometimes not loaded, and i get error about missing class that get called..
    On http addres it is not so bad, since same protocol is used, but evidently, that is evil for https..
    Are Oracle programmers going to fix that?
    As you see, that happens already when loading Jar by Applet Starter and at all, it happens each time on any URLConnection
    Java Plug-in 10.13.2.20
    Using JRE version 1.7.0_13-b20 Java HotSpot(TM) Client VM
    User home directory = X:\Users\admin
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    cache: Initialize resource manager: com.sun.deploy.cache.ResourceProviderImpl@cef147
    security: property package.access value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.
    security: property package.access new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.definition value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.
    security: property package.definition new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.access value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.access new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    security: property package.definition value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp
    security: property package.definition new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    security: property package.access value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    security: property package.access new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss,com.sun.browser,com.sun.glass,com.sun.javafx,com.sun.media.jfxmedia,com.sun.media.jfxmediaimpl,com.sun.openpisces,com.sun.prism,com.sun.scenario,com.sun.t2k,com.sun.webpane,com.sun.pisces,com.sun.webkit
    security: property package.definition value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss
    security: property package.definition new value sun.,com.sun.xml.internal.bind.,com.sun.xml.internal.org.jvnet.staxex.,com.sun.xml.internal.ws.,com.sun.imageio.,com.sun.istack.internal.,com.sun.jmx.defaults.,com.sun.jmx.remote.util.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,com.sun.javaws,com.sun.deploy,com.sun.jnlp,org.mozilla.jss,com.sun.browser,com.sun.glass,com.sun.javafx,com.sun.media.jfxmedia,com.sun.media.jfxmediaimpl,com.sun.openpisces,com.sun.prism,com.sun.scenario,com.sun.t2k,com.sun.webpane,com.sun.pisces,com.sun.webkit
    basic: Added progress listener: sun.plugin.util.ProgressMonitorAdapter@18a2d7d
    basic: Plugin2ClassLoader.addURL parent called for https://www.java.com/jsp_utils/jreverification.jar
    security: Accessing keys and certificate in Mozilla user profile: null
    security: JSS is not configured
    network: Connecting https://www.java.com/jsp_utils/jreverification.jar with proxy=DIRECT
    network: Connecting http://www.java.com:443/ with proxy=DIRECT
    security: Loading Root CA certificates from X:\Program Files\Java\jre7\lib\security\cacerts
    security: Loaded Root CA certificates from X:\Program Files\Java\jre7\lib\security\cacerts
    security: Loading SSL Root CA certificates from X:\Program Files\Java\jre7\lib\security\cacerts
    security: Loaded SSL Root CA certificates from X:\Program Files\Java\jre7\lib\security\cacerts
    security: Loading Deployment SSL certificates from X:\Users\admin\AppData\LocalLow\Sun\Java\Deployment\security\trusted.jssecerts
    security: Loaded Deployment SSL certificates from X:\Users\admin\AppData\LocalLow\Sun\Java\Deployment\security\trusted.jssecerts
    security: Loading certificates from Deployment session certificate store
    security: Loaded certificates from Deployment session certificate store
    security: Checking if certificate is in Deployment denied certificate store
    network: Connecting https://www.java.com/jsp_utils/jreverification.jar with proxy=DIRECT
    network: Connecting http://www.java.com:443/ with proxy=DIRECT
    network: Connecting https://www.java.com/jsp_utils/jreverification.jar with cookie "JSESSIONID=22ABBA2BE9B5789629C276AC35BDF969; s_cc=true; s_nr=1361043522618; gpName=javac%3ADownload%3ATry1_JRE_Homepage; gpChannel=javac%3ADownload; gpServer=www.java.com; s_sq=%5B%5BB%5D%5D"
    network: Downloading resource: https://www.java.com/jsp_utils/jreverification.jar
         Content-Length: 1 306
         Content-Encoding: null
    security: Blacklist revocation check is enabled
    security: The jar file isnt signed so the blacklist check will be skipped
    security: Trusted libraries list check is enabled
    security: Trusted libraries list file not found
    security: The jar file isnt signed so the blacklist check will be skipped
    cache: Adding MemoryCache entry: https://www.java.com/jsp_utils/jreverification.jar
    network: Created version ID: 1.7.0.13
    network: Created version ID: 1.7.0.13
    basic: Applet loaded.
    basic: Applet resized and added to parent container
    basic: PERF: AppletExecutionRunnable - applet.init() BEGIN ; jvmLaunch dt 234287 us, pluginInit dt 7710144 us, TotalTime: 7944431 us
    basic: Applet initialized
    basic: Starting applet
    basic: completed perf rollup
    basic: Applet made visible
    basic: Applet started
    basic: Told clients applet is started
    basic: Starting applet teardown
    basic: Finished applet teardown
    basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter@18a2d7d

    Same problem here. My client uses proxies and https-only web applications. I must keep a network rule to bypass/fix connections on HTTP://....:443/...

  • HttpUrlConnection: Server Error 405

    Hey there!
    What's wrong with my code:
    HttpURLConnection urlConnection = null;
              try {
                   urlConnection = (HttpURLConnection) address.openConnection();
              } catch (IOException e) {
                   e.printStackTrace();
              urlConnection.setRequestProperty("User-Agent",
                        "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
              urlConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
              urlConnection.setDoOutput(true);
              urlConnection.setUseCaches(false);
              for (Enumeration<String> enumeration1 = request.getHeaderNames(); enumeration1
                        .hasMoreElements();) {
                   String headerKeys = enumeration1.nextElement();
                   if (!headerKeys.equals("Content-Type")) {
                        if (headerKeys.indexOf("host") == -1) {
                             urlConnection.setRequestProperty(headerKeys, request
                                       .getHeader(headerKeys));
              try {
                   urlConnection.connect();
              } catch (IOException e) {
                   e.printStackTrace();
              Cookie cookie[] = request.getCookies();
              if (cookie != null) {
                   for (int i = 1; i < cookie.length; i++)
                        urlConnection.setRequestProperty("Set-Cookie" + i,
                                  cookie[i - 1].getName() + "="
                                            + cookie[i - 1].getValue());
              DataOutputStream dataoutputstream = null;
              String encoding = null;
              String contentType = null;
              InputStream inputStream = null;
              try {
                   dataoutputstream = new DataOutputStream(urlConnection
                             .getOutputStream());
                   dataoutputstream.writeBytes(tmp);
                   dataoutputstream.flush();
                   dataoutputstream.close();
                   encoding = urlConnection.getContentEncoding();
                   contentType = urlConnection.getContentType();
                   inputStream = urlConnection.getInputStream();
              } catch (IOException e) {
                   e.printStackTrace();
                  //...This should be a simple Http-Proxy, forwarding incoming requests. It works fine for some sites. However, some servers (e.g. google, heise.de,...) return "Error 405 Method not allowed", when non-html-content (images, scripts,..) are loaded. Any ideas?
    Greetz

    You're writing data with request methods that mightn't allow it, e.g. GET and HEAD.
    But I wouldn't attempt to implement a proxy via HttpURLConnection. Do it all with plain Sockets. It is actually a lot simpler, has less overhead, and will introduce much less latency.

  • Problems with URLConnection

    Hi,
    I am trying to write a small program which makes use of URLConnection.
    Every time I try to read from the url connection it throws EOFException. Please suggest what am I doing wrong. Thanks a lot for all the replies. The code segment is given below.
    clientsocket=serversocket.accept();
    URL url=new URL(urlString);
    HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.connect();
    DataInputStream instream=new DataInputStream(urlConnection.getInputStream());
    DataOutputStream output=new DataOutputStream(clientsocket.getOutputStream());
    byte b1;
    while((b1=instream.readByte())!=-1)   =>exception is thrown here
    output.write(b1);
    output.flush();
    }

    Hi Rohit,
    I haven't tried ur code yet. But, I can give suggestion on how to read from the URLConnection object.
    1) No need to type cast to HttpURLConnection the URLConnection object u get after opening the url. Let it be a normal URLConnection object.
    2) Change the order of setDoInput() and setDoOutput()
    3) Instead of a DataInputStream, use a BufferedInputStream.
    4) Then use the BufferedInputStream object's read() method. For efficiency u can use read(byte[] buff, int offset, int length). For this create a byte buffer first.
    5) In your case, if u want to use BufferedInputStream.read() only, then instead of using a byte variable use an int variable.
    Hope that helps.
    -JP

  • Controling IP addressed used to issue HTTP request

    Hi,
    We are looking for a way to control the IP address we use for outgoing HTTP requests so that we can choose between two IP addresses we will have on a linux server. We have a Linux server running Java/Tomcat which is making HTTP GET requests to Web servers. We want to be able to use one IP address when making requests to one Web server and use a different IP address when making requests to another server. The actual Java method we are using to get the page is connection.getInputStream(), and we get a connection with url.openConnection();
    Is it possible to control which of the server's IP addresses is used for each request, and if so, how? Is there some way we can set up the Linux server or Tomcat to make it work?
    BTW, I believe it is possible to have two IP addresses on a linux server, but I haven't looked into what's involved. Feel free to comment on this if relevant.
    Thanks!

    It is definately possible to have mutliple IP Addresses on a Linux machine.
    As far as setting the local IP Address to bind to when opening a connection, you cannot do this with the Standard HttpURLConnection, HttpsURLConnection, or URLConnection. You can do it, however, using apaches HTTPClient API.

  • Outbound network access limitations

    Hello,
    I would like to know if it is possible from a deployed application in the JCS to get access to secure network resources outside of the JCS. For example, can I get access to a web service provide by google? It seems from the whitelisting app that we're quite limited in terms of networking classes one can use.
    I did a quick test using weblogic.net.http.HttpsURLConnection (which happily passes the whitelist tool), but any connection attempt to secure host fails. Doing a plain http request using java.net.HttpURLConnection does work as expected.
    What are our plans regarding availability of outbound connectivity, more specifically https? Is JCS going to provide a proxy service to monitor and regulate usage of this?
    Thank you,
    Ernst.
    Edited by: Ernst Eeldert on Mar 14, 2013 4:00 PM

    Hmm, still no joy here. You can access the test servlet I wrote at:
    https://java-trialajry.java.us1.oraclecloudapps.com/CloudHerd/outboundtest
    I keep running into access denied issues due to socket usage:
    java.security.AccessControlException: access denied (java.net.SocketPermission 148.87.12.71:443 connect,resolve)
         at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
         at java.security.AccessController.checkPermission(AccessController.java:549)
         at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
         at java.lang.SecurityManager.checkConnect(SecurityManager.java:1034)
         at java.net.Socket.connect(Socket.java:524)
         at weblogic.net.http.HttpsClient.openWrappedSSLSocket(HttpsClient.java:557)
         at weblogic.net.http.HttpsClient.openServer(HttpsClient.java:286)
         at weblogic.net.http.HttpsClient.openServer(HttpsClient.java:363)
         at weblogic.net.http.HttpsClient.New(HttpsClient.java:520)
         at weblogic.net.http.HttpsURLConnection.connect(HttpsURLConnection.java:239)
         at weblogic.net.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:279)
         at oracle.social.demoherd.XClientCloud.post(XClientCloud.java:120)
         at oracle.social.demoherd.XClientCloud.connect(XClientCloud.java:94)
         at oracle.social.demoherd.OutboundTest.doPost(OutboundTest.java:42)
    Here's the code (using weblogic.net.http.HttpsURLConnection):
    URLConnection c = (HttpsURLConnection)new URL(url).openConnection();
    if (APIRANDOMID != null) {
    c.addRequestProperty("X-Waggle-RandomID", APIRANDOMID);
    if (JSESSIONID != null) {
    c.addRequestProperty("Cookie", JSESSIONID.split(";", 2)[0]);
    c.setRequestProperty("Content-Type", "application/json");
    c.setRequestProperty("Accept-Charset", CHARSET);
    c.setRequestProperty("Accept", "application/json");
    ((HttpsURLConnection)c).setHostnameVerifier(DO_NOT_VERIFY);
    c.setConnectTimeout(TIMEOUT);
    Thanks.
    Ernst.

  • Connecting back to applet

    My problem is, im sending a file from an applet to store on the server.
    First of all I do this code which sends all the data to the JSP page
    String base = baseURL.toString();
    String serverBase = base.substring(0,base.indexOf("client"));
    URL serverURL = new URL(serverBase);
    URL url = new URL( "myJSP?scanAction=uploading&imageFileName="+imageFileName+"?tDir="+currentDir);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches (false);      urlConnection.setDefaultUseCaches (false);
    urlConnection.setRequestProperty("content-type", "img/jpeg");      urlConnection.setRequestProperty("content-length", String.valueOf(contentLength));
    //get output stream and write data into
    OutputStream out = urlConnection.getOutputStream();
    out.write(buf);
    out.flush();
    out.close();The JSP page is successfully storing the file on the server.
    Im wanting to send a response to the applet. Im sending a message to the applet like this, however its not working
    out.println("My response from the server");im doing this code in the applet to get the response from the server
    // check scan was ok
    try {
        InputStream is = urlConnection.getInputStream();
        BufferedReader din = new BufferedReader(new InputStreamReader(is));
        Message = Message + din.readLine();
        din.close();
        System.out.println("Message from Server before tinkering: " + Message);
        //check whether upload was successful
        if (Message.equals("OK")) {
            Message = "Uploaded was successful, File size was "+contentLength+"bytes";
        } else {
            Message = "ERROR: Upload falied<BR>"+Message+"<BR><BR>";
    } catch (IOException e) {
        Message = "ERROR: uploading image<BR>"+e.toString()+"<BR><BR>";
        return;
    }However, the variable message is null, so im not sending anything back from the server.
    I quessing that the out.println("blah"); is not th correct way to send a response to the applet,
    What do I need to do?
    TIA, Dale

    Well currently the uloading works fine, Why should I not read the data?
    The orignal code I used has servlets, and these parts of code are what send a response back to the server, the reading of the data is exactly the same the JSP i posted earlier.
    Servlet    response.setContentType("text/html");
        out = response.getWriter();
        out.println("My response from the server");
    JSP    out.println("My response from the server");So why does the servlet send a response back to my applet and my jsp doesn't?
    The only difference is i set the out variable for the servlet where us i dont set the out variable in my jsp as its already set.
    So are these out variables differen't?
    TIA, Dale

  • 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

Maybe you are looking for

  • How do I share files between two Macs using ethernet?

    I have two Macs, both running OS X 10.4.11. How can I connect them using ethernet in order to transfer files back and forth? Pete

  • Error with LSMW IDOC method while maintaining Quota arrangement

    Hi I am trying to create LSMW using IDOC method for maintaining quota Arrangment. I used the standard Message type LPIEQU. Idoc is getting generated and when i tried to process this IDOC i am getting error "Function module not allowed: BAPI_IDOC_INPU

  • Weird holes in text

    I keep getting a weird hole in my text as if there's something the text box with a text wrap when there isn't (just the images on the side). Tried different text, same weird hole. I've managed to get rid of it by clicking 'ignore text wrap' but in th

  • Can we run 2 payrolls on seperate dates within the same payroll area

    Hi, Can someone please tell me is there any possibility in which we can run 2 payroll for seperate PSA and ESG on seperate dates and maintain a commom payroll area for them..? Thanks,

  • Data Binding in BSP - tableview entry not getting deleted.

    Dear Gurus,                 I am very new to the BSP concept.I am told to develop a BSP for creating,updating,deleting entries from a database.I have achieved create and update,But when i am deleting,it gets deleted in backend i.e. in the SAP databas