How to use HttpURLConnection

hi! i'd like to know how to HttpURLConnection. it is an abstract class so i cannot instantiate it direcly. where is the factory to create such a damn object???
by the way...can i use HttpURLConnection to get response from an PHP script? do i have to do the same steps as getting an html document or is it handled different?

To make an HttpURLConnection you need to instantiate a URL object and use openConnection() which returns a URLConnection object, now if the URL use the http or https protocol you can cast it as an HttpURLConnection. Here's some sample code:
java.net.URL address = new java.net.URL("http://www.yahoo.com");
java.net.HttpURLConnectionYahooConn = address.openConnection();You'll need to handle java.net.MalformedURLException when you use new URL(String address)
Cheers

Similar Messages

  • How to use the method  setReadTimeout(int longtimes) in HttpUrlConnection?

    I have to use the HttpUrlConnection to download files ,sometimes the speed is very slow or just blocked for no reason.(no Exception was throw and I can't see any changes from my swing Interface)
    It seems the thread is dead. I try to use setReadTimeout() to control the read . but it isn't working ,
    Now I have to questions?
    one how to use the setReadTimeout() so it can throw the SocketTimeoutException like the API said
    second how to solve the problem I metioned before : sometimes the speed is very slow or just blocked for no reason
    Please somebody help me !!!

    That is not true. For example ajax continuous, http monitor or media streaming in client side is unusable without nio http client (or implementation is much simple and better). All logic is coming to client side from server. Modern client are very powerful and same time servers are overloaded.

  • How do you *unset*  Content-Type when using HttpURLConnection ?

    Hi people,
    I am using HttpURLConnection to set some http headers. It all works fine except that this utility is setting Content-type to text/html even though I cam not coding it to do so. I can overwrite Content-type by setting it to say, a blank, explicitly in the code, but Content-type still appears as a header (eg if I view the headers in a proxy.)
    My question is - how do you completely unset Content-Type? Here's the code snippet :
    URL url = new URL("http://mymachine-uk.uk.company.com:24331/test.html");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setIfModifiedSince(longdate); // I've set up longdate previously
    // set some headers
    con.setRequestProperty("Cache-Control","max-age=0");
    con.setRequestProperty("User-Agent","Mozilla/5.0");
    con.setRequestProperty("Keep-Alive","300");
    // I've tried hacking it like this :
    // con.setRequestProperty("Content-type",null);
    // but that just shows an empty Content-type, rather than get rid of it.
    // In a proxy window on port 24331, the three headers set explicitly above
    // all show up correctly. But Content-type:text/html is also shown, even though not coded.
    // If I fire off the same page request from a browser, Content-type ISN'T set.
    // so there must be a way of doing it :-) Help!
    thanks.
    Edited by: colin_the_aardvark on Feb 24, 2010 1:45 AM

    Hi there,
    thanks very much for trying this, the background to this is as follows :
    I am testing a software server caching product which is giving me weird behaviour; the actions the cache performs are supposed to be based on the various http headers. I am using a debug proxy ("Charles") (limited freeware-for-a-short-period) to see exactly what http headers are being set by the calling browser, or in this case, the java program. I am setting the headers directly in the code above to match what my browser is setting, as revealed by Charles. Trouble is, I'm getting different reponses back: The browser gets a http 304 from the cache and my java program gets a 200, so I have obviously failed to emulate the browser.. and the only difference I can see is that the Conetnt-Type is not set when I call the page from internet explorer, but with my program above, Content-Type is set, to a default of text/html. I want to get rid of it so I have copied the browser http header settings 100%.
    - I tried compiling this code and running it from the prompt (outside of development environment) and Content-Type is still showing up. So from what you are saying... if your attempt does not set this.. then it looks like Content-type must be getting set via some other means?
    thankyou :-)

  • How to receive 100 Continue responses using HttpURLConnection

    Hi there,
    My server returns:
    HTTP/1.1 100 Continue
    Set-Cookie: Cookie1=Value1
    Server: Microsoft-IIS/5.0
    Date: Mon, 29 Sep 2000 18:34:02 GMT
    HTTP/1.0 200 OK
    Server: Server 2
    Set-Cookie: Cookie2=Value2
    Content-Type: text/html
    I'm using HttpURLConnection to get the response.
    I need to get both responses, however HttpURLConnection only returns the 200 OK response.
    How do I get the 100 Continue response using this class? I need it to retrieve the cookie.
    Thanks.

    You can't. If you check the j2se source code you will notice that sun.net.www.http.HttpClient just drops the '100 Continue' and waits for the actual response that follows.

  • How to use URL class instead of Socket

    Hi all. I am developing a small inventory control system for a warehouse.
    I am suing a Java desktop application that connects to a servlet via Internet.
    I have been searching the net how to use JSSE for my application since i am new to secure sockets and JSSE.
    Since I havent implemented security In my current system yet, i am using URLConnection conn = url.openConnection(); to connect to a servlet.
    However, in a good tutorial that I found about JSSE, sockets are used directly for connection, insted of URLCOnnection. They use the code like this: SSLSocketFactory sf = sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); Since, using sockets is overly complex for me, I want to make use of the URLConnection class instead to keep it simple.
    Could anyone please tell me how to make use of the URLConnection class to establish secure http connection.
    by the way, the tutorial is here:
    http://www.panix.com/~mito/articles/articles/jsse/j-jsse-ltr.pdf
    thanks.

    Here you go. The following code snippet allows you post data to http URL. If you have to do the same to https URL , please let me know.
    OutputStream writeOut = null;
    HttpURLConnection appConnection = null;
    URL appUrlOpen = null;
    //data to be posted.
    String data = "This is the test message to post";
    byte[] bytesData = this.data.getBytes();
    appUrlOpen = new URL(""Your Servlet URL");
    appConnection = (HttpURLConnection) appUrlOpen.openConnection();
    appConnection.setDoOutput(true);
    appConnection.setDoInput(true);
    appConnection.setUseCaches(false);
    appConnection.setInstanceFollowRedirects(false);
    appConnection.setRequestMethod("post");
    appConnection.setRequestProperty("Content-Type","application/text");
    appConnection.setRequestProperty("Content-length", String.valueOf(bytesData.length));
    writeOut=appConnection.getOutputStream();
    writeOut.write(bytesData);
    writeOut.flush();
    writeOut.close();
    String inputLine;
    StringBuffer sb = new StringBuffer();
    reader = new BufferedReader(new InputStreamReader(appConnection.getInputStream()));
    char chars[] = new char[1024];
    int len = 0;
    //Write chunks of characters to the StringBuffer
    while ((len = reader.read(chars, 0, chars.length)) >= 0)
    sb.append(chars, 0, len);
    System.out.println("Response " + sb.toString());
    reader.close();
    sb=null;
    chars = null;
    responseBytes = null;
    ******************************************************************************************

  • How to Use XMLHttp without using AJAX in JAVA

    Hi...
    Can any one tell me how to use XMLHttp using Java( not with AJAX or JavaScript). I have one requirement to post one Request to another vendor. that vendor is supporting XMLHttpRequest (developed in ASP). when i try to post request using HttpURLConnection connection it is giving wrong response. But when am posting same request by using VB standalone tool which is using XMLHttp which is provided by vendor it giving correct response.
    please any one tell how to use XMLHttp in JAVA

    Your code will respond to changes in selection.
    To do the same for a JButton you can do:
    JButton button = new JButton("hello world");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // say hello
    //or you could do
    button.addActionListener(al);
    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // hi
    // or use an inner, nested class that implements ActionListener
    // or an inner Action class
    button = new JButton(action);
    private Action action = new AbstractAction("mahbuhi") {
        public void actionPerformed(ActionEvent e) {
            // yes
    // or you could use an outer class that implements ActionListener...
    MyListener l = new MyListener();
    button.add(l);

  • URLConnection.setConnectTimeout(): how to use?

    I wonder how to use URLConnection.setConnectTimeout()? I need to have a URLConnection object (in my case: HttpURLConnection). But the only way to do this for an URL is:
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); right? But then it's too late to set a connection timeout. HttpURLConnection has only a protected constructor, so I can't use it. Is ther another way?

    I don't call connect():
                    con = (HttpURLConnection) url.openConnection(); //can take forever
                    con.setConnectTimeout(timeout);
                    con.setReadTimeout(timeout);
                    //avoid "java.io.IOException: HTTPS hostname wrong:  should be <217.5.135.142>"
                    if (con instanceof HttpsURLConnection) { //HTTPS URL?
                        ((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
                            public boolean verify(String hostname, SSLSession session) {
                                return true;
                    String contentEncoding = con.getContentEncoding();
                    is = con.getInputStream();
                    //get correct input stream for compressed data:
                    if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                        is = new GZIPInputStream(is); //reads 2 bytes to determin GZIP stream!
                    Utils.writeStream(is, outputStream);

  • How to use TorLib to avoid DNS leaks

    Dear Forum Members,
    I need some advice on how best to run Tor in Java when using TorLib to avoid DNS leaks. My difficulty is how to use the TorLib class in the code snippet below to connect to a webserver:
          String url = "http://www.abc.com/index.html",
          URL server = new URL(url);
          Properties systemProperties = System.getProperties();
          systemProperties.setProperty("socks.ProxyHost","localhost");
          systemProperties.setProperty("socks.ProxyPort",9050);
          HttpURLConnection connection = (HttpURLConnection) server.openConnection();
          ......Do I need to instantiate a new socket and how to use it to point to Tor?
    Apologies for asking Tor question in a Java Forum since I could not find the right forum. It would be great if you could direct me to one.
    Any assistance would be appreciated.
    Thanks,
    Jack

    Hi,
    unfortunately, I cannot give support to TorLib, but I can show you an alternative:
    You could use the [silvertunnel Netlib (Tor for Java library)|http://silvertunnel.org/Netlib] as follows:
    // prepare Tor connectivity
    NetLayer lowerNetLayer = NetFacade.getInstance().getNetLayerById(NetLayerIDs.TOR);
    NetlibURLStreamHandlerFactory factory = new NetlibURLStreamHandlerFactory(false);
    factory.setNetLayerForHttpHttpsFtp(lowerNetLayer);
    // create the suitable URL object
    String urlStr = "http://www.abc.com/index.html";
    URLStreamHandler handler = factory.createURLStreamHandler("http");
    URL context = null;
    URL url = new URL(context, urlStr, handler);
    // the rest of this method is as for every java.net.URL object
    URLConnection urlConnection = url.openConnection();
    urlConnection.close();This code communicates over Tor network and has no DNS leak. Docs: [HTTP over Tor in Java with silvertunnel Netlib|http://sourceforge.net/apps/trac/silvertunnel/wiki/NetlibHttp]
    Bye,
    C.

  • How to use one email adress for multiple recipients

    Hello,
    I'd like to know how to use one email adress for multiple recipients. 
    this would be very useful or projects. for example;
    if i send one mail to [email protected], all people in this project get an email.
    I will add the people in this project myself. 
    I know it is possible, but I don't know how to do it ;-)
    please help me! 

    Hope this help.
    _http://technet.microsoft.com/en-us/library/cc164331(v=exchg.65) .aspx

  • Can't figure out how to use home sharing

    Since the latest couple iTunes updates, my family and I can not figure out how to use home sharing. Everyone in our household has their own iTunes, and for a long time we would just share our music through home sharing. But with the updates, so much has changed that we can no longer figure out how to use it.
    I have a lot of purchased albums on another laptop in the house, that im trying to move it all over to my own iTunes, and I have spent a long time searching the internet, and everything. And I just can't figure out how to do it. So.... how does it work now? I would really like to get these albums from my moms iTunes, onto mine. I would hate to have to buy them all over again.
    If anyone is able to help me out here, that would be great! Thanks!

    The problem im having is that after I am in another library through home sharing, I can't figure out how to select an album and import it to my library. They used to have it set up so that you just highlight all of the songs you want, and then all you had to do was click import. Now I don't even see an import button, or anything else like it. So im lost... I don't know if it's something im doing wrong, or if our home sharing system just isn't working properly.
    Thanks for the help.

  • How to use the same POWL query for multiple users

    Hello,
    I have defined a POWL query which executes properly. But if I map the same POWL query to 2 portal users and the 2 portal users try to access the same page simultaneously then it gives an error message to one of the users that
    "Query 'ABC' is already open in another session."
    where 'ABC' is the query name.
    Can you please tell me how to use the same POWL query for multiple users ?
    A fast reply would be highly appreciated.
    Thanks and Regards,
    Sandhya

    Batch processing usually involves using actions you have recorded.  In Action you can insert Path that can be used during processing documents.  Path have some size so you may want to only process document that have the same size.  Look in the Actions Palette fly-out menu for insert path.  It inserts|records the current document work path into the action being worked on and when the action is played it inserts the path into the document as the current work path..

  • How to use airport time capsule with multiple computers?

    I'm sure there are some thread about this but i couldn't find it... so sorry for that but hear me out! =)
    I bought the AirPort Time Capsule to back up my MBP
    And so i did.
    then i thought "let give this one a fresh start" so i erased all of it with the disk utility and re-installed the MBP from the recovery disk.
    I dont want all of the stuff i backed up just a few files and some pictures so i brought that back.. so far so good.
    Now i want to do a new back up of my MBP so i open time machine settings, pick the drive on the time capsule and then "Choose" i wait for the beck up to begin, and then it fails.  It says (sorry for my bad english, im swedish haha) "the mount /Volume/Data-1/StiflersMBP.sparsebundle is already in use for back up.
    this is what i want:
    i want the "StiflersMBP.sparsebundle" to just be so i can get some stuf when i need them. it's never to be erased.
    i want to make a new back up of my MBP as if it's a second computer...
    so guys and girls, what is the easiest and best solution?
    Best regards!

    TM does not work like that.
    If you want files to use later.. do not use TM.
    Or do not use TM to the same location. Plug a USB drive into the computer and use that as the target for the permanent backup.
    Read some details of how TM works so you understand what it will do.
    http://pondini.org/TM/Works.html
    Use a clone or different software for a permanent backup.
    http://pondini.org/TM/Clones.html
    How to use TC
    http://pondini.org/TM/Time_Capsule.html
    This is helpful.. particularly Q3.
    Why you don't want to use TM.
    Q20 here. http://pondini.org/TM/FAQ.html

  • How to use multiple ipods on one account

    I have an Ipod classic and just bought my sons two nano's how do I use these on the same account without changing my account info?

    Take a look here:
    How to use multiple iPods with one computer
    Forum Tip: Since you're new here, you've probably not discovered the Search feature available on every Discussions page, but next time, it might save you time (and everyone else from having to answer the same question multiple times) if you search a couple of ways for a topic, both in the relevant forums, in the User Tips Library and in the Apple Knowledge Base before you post a question.
    Regards.

  • How to use a Table View in AppleScriptObjC

    How can I use a table view and add data to it? And how can I display a button cell and image cell in the table? Thanks.

    Hi all,
    Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
    for ex : select * from (tab_name) where....?
    Can we do inner join on such select statements? If so how?
    Thanks & Regards,
    Mallik.

  • How to use '|' delimited as seprator in GUI_DOWNLOAD ? Plz suggest me ,,

    how to use '|' delimited as seprator in GUI_DOWNLOAD ? Plz suggest me ,,
    i want the output should be seprated by '|' delimited when i download the file.

    Hi,
    We will pass the seperator to the WRITE_FIELD_SEPARATOR parameter as
    CALL FUNCTION 'GUI_DOWNLOAD'
    EXPORTING
    filename = v_file
    write_field_separator = '|'
    TABLES
    data_tab = itab[] . "Our internal talbe filled with data
    Re: Why Function GUI_DOWNLOAD can create XML file but not a flat file?
    Award points if useful
    Thanks,
    Ravee...

Maybe you are looking for