Package java.net

Examples of java.net.HttpURLConnection


        other_params += "&sig=" + sig;
      }
     
      URL target = new URL( SERVICE_URL + "/client/" + command + "?request=" + request_str + other_params );
     
      HttpURLConnection connection = (HttpURLConnection)target.openConnection();
     
      connection.setConnectTimeout( 30*1000 );
     
      InputStream is = connection.getInputStream();
     
      Map<String,Object> response = (Map<String,Object>)BDecoder.decode( new BufferedInputStream( is ));
     
      synchronized( this ){
       
View Full Code Here


              "&app=" + UrlUtils.encode( SystemProperties.getApplicationName()) +
              "&locale=" + UrlUtils.encode( MessageText.getCurrentLocale().toString());
           
            URL target = new URL( SERVICE_URL + "/web/test?sid=" + sid + "&ac=" + access_code + "&format=bencode" + other_params );
           
            HttpURLConnection connection = (HttpURLConnection)target.openConnection();
           
            connection.setConnectTimeout( 10*1000 );
           
            try{
              InputStream is = connection.getInputStream();
             
              Map<String,Object> response = (Map<String,Object>)BDecoder.decode( new BufferedInputStream( is ));
             
              response = BDecoder.decodeStrings( response );
             
View Full Code Here

  private TrustManager[] trustManager;
  private SSLContext sslContext;

  public char monitor(Host host) {
    HttpHost httpHost = (HttpHost) host;
    HttpURLConnection http = null;
    BufferedInputStream bis = null;
    try {
      String urlString = null;

      if (httpHost.isSecure()) {
        urlString = "https://";
      } else {
        urlString = "http://";
      }
      urlString = urlString + httpHost.getInetAddress().getHostAddress()
          + ":" + httpHost.getInetSocketAddress().getPort() + httpHost.getUri();

      URL url = new URL(urlString);
      http = (HttpURLConnection) url.openConnection();
      if (httpHost.isSecure()) {
        HttpsURLConnection https = (HttpsURLConnection) http;

        makeSSLSocketFactory();

        https.setSSLSocketFactory(sslSocketFactory);
        https.setHostnameVerifier(vf);
      }
      http.setRequestMethod("GET");
      http.setDoOutput(true);
      http.setReadTimeout(httpHost.getTimeout());

      http.connect();

      String httpResponseCode = "" + http.getResponseCode();
      if(httpResponseCode.equals(httpHost.getHttpStatusCode())==false) {
        logger.fine("StatusCode does not match.. got "+httpResponseCode+
            ", expected: "+httpHost.getHttpStatusCode());
        return Host.DOWN;
      }

      if (httpHost.getTextToExpect() != null) {
        InputStream is = http.getErrorStream();
        if(is==null) {
          is = http.getInputStream();
        }
        bis = new BufferedInputStream(is);
       
        String textGot = new String(BlockingClient.readInputStream(bis), "utf-8");
        if (textGot.indexOf(httpHost.getTextToExpect()) != -1) {
          return Host.ACTIVE;
        } else {
          logger.fine(httpHost + " Error: Text [" + httpHost.getTextToExpect()
              + "]Not found! Got: " + textGot);
          return Host.DOWN;
        }
      } else {
        return Host.ACTIVE;
      }
    } catch (IOException e) {
      logger.fine(httpHost + " IOError: " + e);
      return Host.DOWN;
    } catch (Exception e) {
      logger.warning(httpHost + " Error: " + e);
      return Host.ERROR;
    } finally {
      if(bis!=null) {
        try {
          bis.close();
        } catch (IOException ex) {
          Logger.getLogger(HttpMonitor.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
      if (http != null) {
        http.disconnect();
       
      }
      host.setLastCheckedOn(new Date());
    }
  }
View Full Code Here

    String        str )
  {
    try{
      URL  url = new URL( str );
     
      HttpURLConnection con = (HttpURLConnection)url.openConnection();
     
      UrlUtils.setBrowserHeaders( con, null );
     
      String  key = "cn." + cn.getID() + ".identify.cookie";
     
      String cookie = COConfigurationManager.getStringParameter( key, null );
     
      if ( cookie != null ){
       
        con.setRequestProperty( "Cookie", cookie + ";" );
      }
     
      con.setRequestProperty( "Connection", "close" );
     
      con.getResponseCode();
     
      cookie = con.getHeaderField( "Set-Cookie" );
     
      if ( cookie != null ){
       
        String[] bits = cookie.split( ";" );
       
View Full Code Here

  protected boolean
  linkIsToTorrent(
    URL    url )
  {
    try{
      HttpURLConnection con = (HttpURLConnection)url.openConnection();
     
      con.setRequestMethod( "HEAD" );
     
      con.setConnectTimeout( 10*1000 );
     
      con.setReadTimeout( 10*1000 );
     
      String content_type = con.getContentType();

      log( "Testing link " + url + " to see if torrent link -> content type=" + content_type );
     
      if ( content_type.equalsIgnoreCase( "application/x-bittorrent" )){
       
View Full Code Here

            raf = new RandomAccessFile( scratch_file, "rw" );
          }
                   
          // System.out.println( "Connecting to " + url + ": " + Thread.currentThread().getId());
 
          HttpURLConnection  connection;
          int          response;
         
          connection = (HttpURLConnection)original_url.openConnection();
           
          connection.setRequestProperty( "Connection", "Keep-Alive" );
          connection.setRequestProperty( "User-Agent", user_agent );
           
          int  time_remaining  = listener.getPermittedTime();
         
          if ( time_remaining > 0 ){
           
            Java15Utils.setConnectTimeout( connection, time_remaining );
          }
               
          connection.connect();
       
          time_remaining  = listener.getPermittedTime();
                   
          if ( time_remaining < 0 ){
           
            throw( new IOException( "Timeout during connect" ));
          }
         
          Java15Utils.setReadTimeout( connection, time_remaining );
             
          connected  = true;
         
          response = connection.getResponseCode();
         
          last_response  = response;
         
          last_response_retry_after_secs  = -1;
         
                if ( response == 503 ){
                              
                      // webseed support for temp unavail - read the retry_after
                 
                  long retry_after_date = new Long(connection.getHeaderFieldDate("Retry-After", -1L)).longValue();
                 
                    if ( retry_after_date <= -1 ){
                     
                      last_response_retry_after_secs = connection.getHeaderFieldInt("Retry-After", -1);
                       
                    }else{
                     
                      last_response_retry_after_secs = (int)((retry_after_date - System.currentTimeMillis())/1000);
                     
                      if ( last_response_retry_after_secs < 0 ){
                       
                        last_response_retry_after_secs = -1;
                      }
                    }
                }
               
          is = connection.getInputStream();
         
          if (   response == HttpURLConnection.HTTP_ACCEPTED ||
              response == HttpURLConnection.HTTP_OK ||
              response == HttpURLConnection.HTTP_PARTIAL ){
           
            byte[]  buffer = new byte[64*1024];
           
            int  requests_outstanding = 1// should be one at least
           
            while( !destroyed ){
                         
              int  permitted = listener.getPermittedBytes();
             
                // idle if no reqs
             
              if ( requests_outstanding == 0 || permitted < 1 ){
               
                permitted = 1;
               
                Thread.sleep( 100 );
              }
             
              int  len = is.read( buffer, 0, Math.min( permitted, buffer.length ));
             
              if ( len <= 0 ){
               
                break;
              }
             
              synchronized( this ){
             
                try{
                  raf.write( buffer, 0, len );
                 
                }catch( Throwable e ){
                 
                    // assume out of space of something permanent, abandon
                 
                  outcome = "Write failed: " + e.getMessage();
                 
                  ExternalSeedException  error = new ExternalSeedException( outcome, e );
                 
                  error.setPermanentFailure( true );
                 
                  throw( error );
                }
              }
             
              listener.reportBytesRead( len );
             
              requests_outstanding = checkRequests();
            }
           
            checkRequests();
           
          }else{
           
            outcome = "Connection failed: " + connection.getResponseMessage();
           
            ExternalSeedException  error = new ExternalSeedException( outcome );
           
            error.setPermanentFailure( true );
           
View Full Code Here

    try{
      SESecurityManager.setThreadPasswordHandler( this );
     
      // System.out.println( "Connecting to " + url + ": " + Thread.currentThread().getId());

      HttpURLConnection  connection;
      int          response;
     
      while( true ){
       
        URL  target = redirected_url==null?original_url:redirected_url;
       
        connection = (HttpURLConnection)target.openConnection();
       
        connection.setRequestProperty( "Connection", "Keep-Alive" );
        connection.setRequestProperty( "User-Agent", user_agent );
       
        for (int i=0;i<prop_names.length;i++){
         
          connection.setRequestProperty( prop_names[i], prop_values[i] );
        }
       
        int  time_remaining  = listener.getPermittedTime();
       
        if ( time_remaining > 0 ){
         
          Java15Utils.setConnectTimeout( connection, time_remaining );
        }
             
        connection.connect();
     
        time_remaining  = listener.getPermittedTime();
                 
        if ( time_remaining < 0 ){
         
          throw( new IOException( "Timeout during connect" ));
        }
       
        Java15Utils.setReadTimeout( connection, time_remaining );
           
        connected  = true;
       
        response = connection.getResponseCode();

        if response == HttpURLConnection.HTTP_ACCEPTED ||
            response == HttpURLConnection.HTTP_OK ||
            response == HttpURLConnection.HTTP_PARTIAL ){
         
          if ( redirected_url != null ){
           
            consec_redirect_fails = 0;
          }
         
          break;
        }
       
        if ( redirected_url == null ){
         
          break;
        }
       
          // try again with original URL
       
        consec_redirect_fails++;
       
        redirected_url = null;
      }
     
      URL final_url = connection.getURL();
     
      if ( consec_redirect_fails < 10 && !original_url.toExternalForm().equals( final_url.toExternalForm())){
       
        redirected_url = final_url;
      }
     
      last_response  = response;
     
      last_response_retry_after_secs  = -1;
     
            if ( response == 503 ){
                          
                  // webseed support for temp unavail - read the retry_after
             
              long retry_after_date = new Long(connection.getHeaderFieldDate("Retry-After", -1L)).longValue();
             
                if ( retry_after_date <= -1 ){
                 
                  last_response_retry_after_secs = connection.getHeaderFieldInt("Retry-After", -1);
                   
                }else{
                 
                  last_response_retry_after_secs = (int)((retry_after_date - System.currentTimeMillis())/1000);
                 
                  if ( last_response_retry_after_secs < 0 ){
                   
                    last_response_retry_after_secs = -1;
                  }
                }
            }
           
      is = connection.getInputStream();
     
      if (   response == HttpURLConnection.HTTP_ACCEPTED ||
          response == HttpURLConnection.HTTP_OK ||
          response == HttpURLConnection.HTTP_PARTIAL ){
               
        int  pos = 0;
       
        byte[]  buffer     = null;
        int    buffer_pos  = 0;
        int    buffer_len  = 0;

        while( pos < length ){
         
          if ( buffer == null ){
           
            buffer     = listener.getBuffer();           
            buffer_pos  = listener.getBufferPosition();
            buffer_len  = listener.getBufferLength();
          }

          listener.setBufferPosition( buffer_pos );
         
          int  to_read = buffer_len - buffer_pos;
         
          int  permitted = listener.getPermittedBytes();
         
          if ( permitted < to_read ){
           
            to_read  = permitted;
          }
         
          int  len = is.read( buffer, buffer_pos, to_read );
         
          if ( len < 0 ){
           
            break;
          }
         
          listener.reportBytesRead( len );
         
          pos  += len;
         
          buffer_pos  += len;
         
          if ( buffer_pos == buffer_len ){
           
            listener.done();
           
            buffer    = null;
            buffer_pos  = 0;
          }
        }
       
        if ( pos != length ){
         
          String  log_str;
         
          if ( buffer == null ){
           
            log_str = "No buffer assigned";
           
          }else{
           
            log_str =  new String( buffer, 0, length );
           
            if ( log_str.length() > 64 ){
             
              log_str = log_str.substring( 0, 64 );
            }
          }
         
          outcome = "Connection failed: data too short - " + length + "/" + pos + " [" + log_str + "]";
         
          throw( new ExternalSeedException( outcome ));
        }
       
        outcome = "read " + pos + " bytes";
       
        // System.out.println( "download length: " + pos );
       
      }else{
       
        outcome = "Connection failed: " + connection.getResponseMessage();
       
        ExternalSeedException  error = new ExternalSeedException( outcome );
       
        error.setPermanentFailure( true );
       
View Full Code Here

        return url.openConnection();
    }

    public static URLConnection httpPost(WebServer webServer, String path, String body) throws IOException {
        URL url = new URL(webServer.getUri().toURL(), path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        urlConnection.setDoOutput(true);
        urlConnection.getOutputStream().write(body.getBytes(Charset.forName("UTF8")));
        return urlConnection;
    }
View Full Code Here

                connection = url.openConnection();
            }
            connection.setDoOutput(true);

            if (connection instanceof HttpURLConnection) {
                HttpURLConnection hc = (HttpURLConnection)connection;
                hc.setRequestMethod("POST");
            }

            connection.setConnectTimeout((int)policy.getConnectionTimeout());
            connection.setReadTimeout((int)policy.getReceiveTimeout());

            connection.setUseCaches(false);
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection hc = (HttpURLConnection)connection;
                if (policy.isAutoRedirect()) {
                    //cannot use chunking if autoredirect as the request will need to be
                    //completely cached locally and resent to the redirect target
                    hc.setInstanceFollowRedirects(true);
                } else {
                    hc.setInstanceFollowRedirects(false);
                    if (policy.isAllowChunking()) {
                        hc.setChunkedStreamingMode(2048);
                    }
                }
            }
            setPolicies(headers);
            if (connection instanceof HttpsURLConnection) {
View Full Code Here

            if (!initialised) {
                put(ObjectMessageContext.MESSAGE_INPUT, false);
                put(HTTP_RESPONSE_HEADERS, connection.getHeaderFields());
                put(HTTP_RESPONSE_CODE, getResponseCode(connection));
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection hc = (HttpURLConnection)connection;
                    origInputStream = hc.getErrorStream();
                    if (null == origInputStream) {
                        origInputStream = connection.getInputStream();
                    }
                } else {
                    origInputStream = connection.getInputStream();
View Full Code Here

TOP

Related Classes of java.net.HttpURLConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.