in HTTP mode they is not initial connection concept adapter as to handle data.
324556
function HttpRequest (request, response) {
        this.gateway.Debug(7, "Data=[%s]", request.url);

        var question=url.parse(request.url, true, true);
        var query=question.query;

        var batchRequest = new BatchRequest(this.gateway, query, response);
        var command = path.basename(question.pathname);
        var tracker = true;

        if (query.phonenum == undefined) {
            this.gateway.Debug (0,"Hoops phonenum undefined");
            response.writeHeader(400, {"Content-Type": "text/plain"});
            response.write('ERR: AjaxSMS check-phonenum missing phonenum=xxxxx');
            response.end();
            return;
        }

        switch (command)  {

            case "check-dev-mobile":
                tracker=false;
            case "check-dev-tracker": // http://geotobe.localnet/smsgateway/check-dev-tracker?phonenum=+33782849007&passwd=123456&apn=free&host=46.105.45.122&port=4010
                batchRequest.CheckTrackerBySms(tracker, query);
                break;

            case "send-sms-text":
                batchRequest.SendSmsText(tracker, query);
                break;

            case 'check-accesscode':
                this.backend.getByEmei(batchRequest.CheckAccessCode, query.imeinum);
                break;

            default:
                response.writeHeader(400, {"Content-Type": "text/plain"});
                response.write('ERR: AjaxSMS command: ['+ command + '] in Http Request');
                response.end();
        }

    }
1255766
@Override
	public void setConnectionTimeoutMS(int connectionTimeoutMS) {
    	connectionManager.getParams().setConnectionTimeout(connectionTimeoutMS);
    	http.getParams().setConnectionManagerTimeout(connectionTimeoutMS);
	}
1324710
def connection
      options = { url: api_url, ssl: { verify: false } }

      connection = Faraday.new(options) do |conn|
        conn.response :readmill_errors
        conn.response :mashify
        conn.response :json

        conn.adapter  adapter
      end

      connection
    end
78534
public static void nonProxyHosts(final String... hosts) {
    if (hosts != null && hosts.length > 0) {
      StringBuilder separated = new StringBuilder();
      int last = hosts.length - 1;
      for (int i = 0; i < last; i++)
        separated.append(hosts[i]).append('|');
      separated.append(hosts[last]);
      setProperty("http.nonProxyHosts", separated.toString());
    } else
      setProperty("http.nonProxyHosts", null);
  }

  /**
   * Set property to given value.
   * <p>
   * Specifying a null value will cause the property to be cleared
   *
   * @param name
   * @param value
   * @return previous value
   */
  private static String setProperty(final String name, final String value) {
    final PrivilegedAction<String> action;
    if (value != null)
      action = new PrivilegedAction<String>() {

        public String run() {
          return System.setProperty(name, value);
        }
      };
    else
      action = new PrivilegedAction<String>() {

        public String run() {
          return System.clearProperty(name);
        }
      };
    return AccessController.doPrivileged(action);
  }

  private HttpURLConnection connection = null;

  private final URL url;

  private final String requestMethod;

  private RequestOutputStream output;

  private boolean multipart;

  private boolean form;

  private boolean ignoreCloseExceptions = true;

  private boolean uncompress = false;

  private int bufferSize = 8192;

  private long totalSize = -1;

  private long totalWritten = 0;

  private String httpProxyHost;

  private int httpProxyPort;

  private UploadProgress progress = UploadProgress.DEFAULT;

  /**
   * Create HTTP connection wrapper
   *
   * @param url Remote resource URL.
   * @param method HTTP request method (e.g., "GET", "POST").
   * @throws HttpRequestException
   */
  public HttpRequest(final CharSequence url, final String method)
      throws HttpRequestException {
    try {
      this.url = new URL(url.toString());
    } catch (MalformedURLException e) {
      throw new HttpRequestException(e);
    }
    this.requestMethod = method;
  }

  /**
   * Create HTTP connection wrapper
   *
   * @param url Remote resource URL.
   * @param method HTTP request method (e.g., "GET", "POST").
   * @throws HttpRequestException
   */
  public HttpRequest(final URL url, final String method)
      throws HttpRequestException {
    this.url = url;
    this.requestMethod = method;
  }

  private Proxy createProxy() {
    return new Proxy(HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
  }

  private HttpURLConnection createConnection() {
    try {
      final HttpURLConnection connection;
      if (httpProxyHost != null)
        connection = CONNECTION_FACTORY.create(url, createProxy());
      else
        connection = CONNECTION_FACTORY.create(url);
      connection.setRequestMethod(requestMethod);
      return connection;
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  @Override
  public String toString() {
    return method() + ' ' + url();
  }

  /**
   * Get underlying connection
   *
   * @return connection
   */
  public HttpURLConnection getConnection() {
    if (connection == null)
      connection = createConnection();
    return connection;
  }

  /**
   * Set whether or not to ignore exceptions that occur from calling
   * {@link Closeable#close()}
   * <p>
   * The default value of this setting is <code>true</code>
   *
   * @param ignore
   * @return this request
   */
  public HttpRequest ignoreCloseExceptions(final boolean ignore) {
    ignoreCloseExceptions = ignore;
    return this;
  }

  /**
   * Get whether or not exceptions thrown by {@link Closeable#close()} are
   * ignored
   *
   * @return true if ignoring, false if throwing
   */
  public boolean ignoreCloseExceptions() {
    return ignoreCloseExceptions;
  }

  /**
   * Get the status code of the response
   *
   * @return the response code
   * @throws HttpRequestException
   */
  public int code() throws HttpRequestException {
    try {
      closeOutput();
      return getConnection().getResponseCode();
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Set the value of the given {@link AtomicInteger} to the status code of the
   * response
   *
   * @param output
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest code(final AtomicInteger output)
      throws HttpRequestException {
    output.set(code());
    return this;
  }

  /**
   * Is the response code a 200 OK?
   *
   * @return true if 200, false otherwise
   * @throws HttpRequestException
   */
  public boolean ok() throws HttpRequestException {
    return HTTP_OK == code();
  }

  /**
   * Is the response code a 201 Created?
   *
   * @return true if 201, false otherwise
   * @throws HttpRequestException
   */
  public boolean created() throws HttpRequestException {
    return HTTP_CREATED == code();
  }

  /**
   * Is the response code a 204 No Content?
   *
   * @return true if 204, false otherwise
   * @throws HttpRequestException
   */
  public boolean noContent() throws HttpRequestException {
    return HTTP_NO_CONTENT == code();
  }

  /**
   * Is the response code a 500 Internal Server Error?
   *
   * @return true if 500, false otherwise
   * @throws HttpRequestException
   */
  public boolean serverError() throws HttpRequestException {
    return HTTP_INTERNAL_ERROR == code();
  }

  /**
   * Is the response code a 400 Bad Request?
   *
   * @return true if 400, false otherwise
   * @throws HttpRequestException
   */
  public boolean badRequest() throws HttpRequestException {
    return HTTP_BAD_REQUEST == code();
  }

  /**
   * Is the response code a 404 Not Found?
   *
   * @return true if 404, false otherwise
   * @throws HttpRequestException
   */
  public boolean notFound() throws HttpRequestException {
    return HTTP_NOT_FOUND == code();
  }

  /**
   * Is the response code a 304 Not Modified?
   *
   * @return true if 304, false otherwise
   * @throws HttpRequestException
   */
  public boolean notModified() throws HttpRequestException {
    return HTTP_NOT_MODIFIED == code();
  }

  /**
   * Get status message of the response
   *
   * @return message
   * @throws HttpRequestException
   */
  public String message() throws HttpRequestException {
    try {
      closeOutput();
      return getConnection().getResponseMessage();
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Disconnect the connection
   *
   * @return this request
   */
  public HttpRequest disconnect() {
    getConnection().disconnect();
    return this;
  }

  /**
   * Set chunked streaming mode to the given size
   *
   * @param size
   * @return this request
   */
  public HttpRequest chunk(final int size) {
    getConnection().setChunkedStreamingMode(size);
    return this;
  }

  /**
   * Set the size used when buffering and copying between streams
   * <p>
   * This size is also used for send and receive buffers created for both char
   * and byte arrays
   * <p>
   * The default buffer size is 8,192 bytes
   *
   * @param size
   * @return this request
   */
  public HttpRequest bufferSize(final int size) {
    if (size < 1)
      throw new IllegalArgumentException("Size must be greater than zero");
    bufferSize = size;
    return this;
  }

  /**
   * Get the configured buffer size
   * <p>
   * The default buffer size is 8,192 bytes
   *
   * @return buffer size
   */
  public int bufferSize() {
    return bufferSize;
  }

  /**
   * Set whether or not the response body should be automatically uncompressed
   * when read from.
   * <p>
   * This will only affect requests that have the 'Content-Encoding' response
   * header set to 'gzip'.
   * <p>
   * This causes all receive methods to use a {@link GZIPInputStream} when
   * applicable so that higher level streams and readers can read the data
   * uncompressed.
   * <p>
   * Setting this option does not cause any request headers to be set
   * automatically so {@link #acceptGzipEncoding()} should be used in
   * conjunction with this setting to tell the server to gzip the response.
   *
   * @param uncompress
   * @return this request
   */
  public HttpRequest uncompress(final boolean uncompress) {
    this.uncompress = uncompress;
    return this;
  }

  /**
   * Create byte array output stream
   *
   * @return stream
   */
  protected ByteArrayOutputStream byteStream() {
    final int size = contentLength();
    if (size > 0)
      return new ByteArrayOutputStream(size);
    else
      return new ByteArrayOutputStream();
  }

  /**
   * Get response as {@link String} in given character set
   * <p>
   * This will fall back to using the UTF-8 character set if the given charset
   * is null
   *
   * @param charset
   * @return string
   * @throws HttpRequestException
   */
  public String body(final String charset) throws HttpRequestException {
    final ByteArrayOutputStream output = byteStream();
    try {
      copy(buffer(), output);
      return output.toString(getValidCharset(charset));
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Get response as {@link String} using character set returned from
   * {@link #charset()}
   *
   * @return string
   * @throws HttpRequestException
   */
  public String body() throws HttpRequestException {
    return body(charset());
  }

  /**
   * Get the response body as a {@link String} and set it as the value of the
   * given reference.
   *
   * @param output
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest body(final AtomicReference<String> output) throws HttpRequestException {
    output.set(body());
    return this;
  }

  /**
   * Get the response body as a {@link String} and set it as the value of the
   * given reference.
   *
   * @param output
   * @param charset
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest body(final AtomicReference<String> output, final String charset) throws HttpRequestException {
    output.set(body(charset));
    return this;
  }


  /**
   * Is the response body empty?
   *
   * @return true if the Content-Length response header is 0, false otherwise
   * @throws HttpRequestException
   */
  public boolean isBodyEmpty() throws HttpRequestException {
    return contentLength() == 0;
  }

  /**
   * Get response as byte array
   *
   * @return byte array
   * @throws HttpRequestException
   */
  public byte[] bytes() throws HttpRequestException {
    final ByteArrayOutputStream output = byteStream();
    try {
      copy(buffer(), output);
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return output.toByteArray();
  }

  /**
   * Get response in a buffered stream
   *
   * @see #bufferSize(int)
   * @return stream
   * @throws HttpRequestException
   */
  public BufferedInputStream buffer() throws HttpRequestException {
    return new BufferedInputStream(stream(), bufferSize);
  }

  /**
   * Get stream to response body
   *
   * @return stream
   * @throws HttpRequestException
   */
  public InputStream stream() throws HttpRequestException {
    InputStream stream;
    if (code() < HTTP_BAD_REQUEST)
      try {
        stream = getConnection().getInputStream();
      } catch (IOException e) {
        throw new HttpRequestException(e);
      }
    else {
      stream = getConnection().getErrorStream();
      if (stream == null)
        try {
          stream = getConnection().getInputStream();
        } catch (IOException e) {
          if (contentLength() > 0)
            throw new HttpRequestException(e);
          else
            stream = new ByteArrayInputStream(new byte[0]);
        }
    }

    if (!uncompress || !ENCODING_GZIP.equals(contentEncoding()))
      return stream;
    else
      try {
        return new GZIPInputStream(stream);
      } catch (IOException e) {
        throw new HttpRequestException(e);
      }
  }

  /**
   * Get reader to response body using given character set.
   * <p>
   * This will fall back to using the UTF-8 character set if the given charset
   * is null
   *
   * @param charset
   * @return reader
   * @throws HttpRequestException
   */
  public InputStreamReader reader(final String charset)
      throws HttpRequestException {
    try {
      return new InputStreamReader(stream(), getValidCharset(charset));
    } catch (UnsupportedEncodingException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Get reader to response body using the character set returned from
   * {@link #charset()}
   *
   * @return reader
   * @throws HttpRequestException
   */
  public InputStreamReader reader() throws HttpRequestException {
    return reader(charset());
  }

  /**
   * Get buffered reader to response body using the given character set r and
   * the configured buffer size
   *
   *
   * @see #bufferSize(int)
   * @param charset
   * @return reader
   * @throws HttpRequestException
   */
  public BufferedReader bufferedReader(final String charset)
      throws HttpRequestException {
    return new BufferedReader(reader(charset), bufferSize);
  }

  /**
   * Get buffered reader to response body using the character set returned from
   * {@link #charset()} and the configured buffer size
   *
   * @see #bufferSize(int)
   * @return reader
   * @throws HttpRequestException
   */
  public BufferedReader bufferedReader() throws HttpRequestException {
    return bufferedReader(charset());
  }

  /**
   * Stream response body to file
   *
   * @param file
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest receive(final File file) throws HttpRequestException {
    final OutputStream output;
    try {
      output = new BufferedOutputStream(new FileOutputStream(file), bufferSize);
    } catch (FileNotFoundException e) {
      throw new HttpRequestException(e);
    }
    return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) {

      @Override
      protected HttpRequest run() throws HttpRequestException, IOException {
        return receive(output);
      }
    }.call();
  }

  /**
   * Stream response to given output stream
   *
   * @param output
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest receive(final OutputStream output)
      throws HttpRequestException {
    try {
      return copy(buffer(), output);
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Stream response to given print stream
   *
   * @param output
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest receive(final PrintStream output)
      throws HttpRequestException {
    return receive((OutputStream) output);
  }

  /**
   * Receive response into the given appendable
   *
   * @param appendable
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest receive(final Appendable appendable)
      throws HttpRequestException {
    final BufferedReader reader = bufferedReader();
    return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {

      @Override
      public HttpRequest run() throws IOException {
        final CharBuffer buffer = CharBuffer.allocate(bufferSize);
        int read;
        while ((read = reader.read(buffer)) != -1) {
          buffer.rewind();
          appendable.append(buffer, 0, read);
          buffer.rewind();
        }
        return HttpRequest.this;
      }
    }.call();
  }

  /**
   * Receive response into the given writer
   *
   * @param writer
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest receive(final Writer writer) throws HttpRequestException {
    final BufferedReader reader = bufferedReader();
    return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {

      @Override
      public HttpRequest run() throws IOException {
        return copy(reader, writer);
      }
    }.call();
  }

  /**
   * Set read timeout on connection to given value
   *
   * @param timeout
   * @return this request
   */
  public HttpRequest readTimeout(final int timeout) {
    getConnection().setReadTimeout(timeout);
    return this;
  }

  /**
   * Set connect timeout on connection to given value
   *
   * @param timeout
   * @return this request
   */
  public HttpRequest connectTimeout(final int timeout) {
    getConnection().setConnectTimeout(timeout);
    return this;
  }

  /**
   * Set header name to given value
   *
   * @param name
   * @param value
   * @return this request
   */
  public HttpRequest header(final String name, final String value) {
    getConnection().setRequestProperty(name, value);
    return this;
  }

  /**
   * Set header name to given value
   *
   * @param name
   * @param value
   * @return this request
   */
  public HttpRequest header(final String name, final Number value) {
    return header(name, value != null ? value.toString() : null);
  }

  /**
   * Set all headers found in given map where the keys are the header names and
   * the values are the header values
   *
   * @param headers
   * @return this request
   */
  public HttpRequest headers(final Map<String, String> headers) {
    if (!headers.isEmpty())
      for (Entry<String, String> header : headers.entrySet())
        header(header);
    return this;
  }

  /**
   * Set header to have given entry's key as the name and value as the value
   *
   * @param header
   * @return this request
   */
  public HttpRequest header(final Entry<String, String> header) {
    return header(header.getKey(), header.getValue());
  }

  /**
   * Get a response header
   *
   * @param name
   * @return response header
   * @throws HttpRequestException
   */
  public String header(final String name) throws HttpRequestException {
    closeOutputQuietly();
    return getConnection().getHeaderField(name);
  }

  /**
   * Get all the response headers
   *
   * @return map of response header names to their value(s)
   * @throws HttpRequestException
   */
  public Map<String, List<String>> headers() throws HttpRequestException {
    closeOutputQuietly();
    return getConnection().getHeaderFields();
  }

  /**
   * Get a date header from the response falling back to returning -1 if the
   * header is missing or parsing fails
   *
   * @param name
   * @return date, -1 on failures
   * @throws HttpRequestException
   */
  public long dateHeader(final String name) throws HttpRequestException {
    return dateHeader(name, -1L);
  }

  /**
   * Get a date header from the response falling back to returning the given
   * default value if the header is missing or parsing fails
   *
   * @param name
   * @param defaultValue
   * @return date, default value on failures
   * @throws HttpRequestException
   */
  public long dateHeader(final String name, final long defaultValue)
      throws HttpRequestException {
    closeOutputQuietly();
    return getConnection().getHeaderFieldDate(name, defaultValue);
  }

  /**
   * Get an integer header from the response falling back to returning -1 if the
   * header is missing or parsing fails
   *
   * @param name
   * @return header value as an integer, -1 when missing or parsing fails
   * @throws HttpRequestException
   */
  public int intHeader(final String name) throws HttpRequestException {
    return intHeader(name, -1);
  }

  /**
   * Get an integer header value from the response falling back to the given
   * default value if the header is missing or if parsing fails
   *
   * @param name
   * @param defaultValue
   * @return header value as an integer, default value when missing or parsing
   *         fails
   * @throws HttpRequestException
   */
  public int intHeader(final String name, final int defaultValue)
      throws HttpRequestException {
    closeOutputQuietly();
    return getConnection().getHeaderFieldInt(name, defaultValue);
  }

  /**
   * Get all values of the given header from the response
   *
   * @param name
   * @return non-null but possibly empty array of {@link String} header values
   */
  public String[] headers(final String name) {
    final Map<String, List<String>> headers = headers();
    if (headers == null || headers.isEmpty())
      return EMPTY_STRINGS;

    final List<String> values = headers.get(name);
    if (values != null && !values.isEmpty())
      return values.toArray(new String[values.size()]);
    else
      return EMPTY_STRINGS;
  }

  /**
   * Get parameter with given name from header value in response
   *
   * @param headerName
   * @param paramName
   * @return parameter value or null if missing
   */
  public String parameter(final String headerName, final String paramName) {
    return getParam(header(headerName), paramName);
  }

  /**
   * Get all parameters from header value in response
   * <p>
   * This will be all key=value pairs after the first ';' that are separated by
   * a ';'
   *
   * @param headerName
   * @return non-null but possibly empty map of parameter headers
   */
  public Map<String, String> parameters(final String headerName) {
    return getParams(header(headerName));
  }

  /**
   * Get parameter values from header value
   *
   * @param header
   * @return parameter value or null if none
   */
  protected Map<String, String> getParams(final String header) {
    if (header == null || header.length() == 0)
      return Collections.emptyMap();

    final int headerLength = header.length();
    int start = header.indexOf(';') + 1;
    if (start == 0 || start == headerLength)
      return Collections.emptyMap();

    int end = header.indexOf(';', start);
    if (end == -1)
      end = headerLength;

    Map<String, String> params = new LinkedHashMap<String, String>();
    while (start < end) {
      int nameEnd = header.indexOf('=', start);
      if (nameEnd != -1 && nameEnd < end) {
        String name = header.substring(start, nameEnd).trim();
        if (name.length() > 0) {
          String value = header.substring(nameEnd + 1, end).trim();
          int length = value.length();
          if (length != 0)
            if (length > 2 && '"' == value.charAt(0)
                && '"' == value.charAt(length - 1))
              params.put(name, value.substring(1, length - 1));
            else
              params.put(name, value);
        }
      }

      start = end + 1;
      end = header.indexOf(';', start);
      if (end == -1)
        end = headerLength;
    }

    return params;
  }

  /**
   * Get parameter value from header value
   *
   * @param value
   * @param paramName
   * @return parameter value or null if none
   */
  protected String getParam(final String value, final String paramName) {
    if (value == null || value.length() == 0)
      return null;

    final int length = value.length();
    int start = value.indexOf(';') + 1;
    if (start == 0 || start == length)
      return null;

    int end = value.indexOf(';', start);
    if (end == -1)
      end = length;

    while (start < end) {
      int nameEnd = value.indexOf('=', start);
      if (nameEnd != -1 && nameEnd < end
          && paramName.equals(value.substring(start, nameEnd).trim())) {
        String paramValue = value.substring(nameEnd + 1, end).trim();
        int valueLength = paramValue.length();
        if (valueLength != 0)
          if (valueLength > 2 && '"' == paramValue.charAt(0)
              && '"' == paramValue.charAt(valueLength - 1))
            return paramValue.substring(1, valueLength - 1);
          else
            return paramValue;
      }

      start = end + 1;
      end = value.indexOf(';', start);
      if (end == -1)
        end = length;
    }

    return null;
  }

  /**
   * Get 'charset' parameter from 'Content-Type' response header
   *
   * @return charset or null if none
   */
  public String charset() {
    return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET);
  }

  /**
   * Set the 'User-Agent' header to given value
   *
   * @param userAgent
   * @return this request
   */
  public HttpRequest userAgent(final String userAgent) {
    return header(HEADER_USER_AGENT, userAgent);
  }

  /**
   * Set the 'Referer' header to given value
   *
   * @param referer
   * @return this request
   */
  public HttpRequest referer(final String referer) {
    return header(HEADER_REFERER, referer);
  }

  /**
   * Set value of {@link HttpURLConnection#setUseCaches(boolean)}
   *
   * @param useCaches
   * @return this request
   */
  public HttpRequest useCaches(final boolean useCaches) {
    getConnection().setUseCaches(useCaches);
    return this;
  }

  /**
   * Set the 'Accept-Encoding' header to given value
   *
   * @param acceptEncoding
   * @return this request
   */
  public HttpRequest acceptEncoding(final String acceptEncoding) {
    return header(HEADER_ACCEPT_ENCODING, acceptEncoding);
  }

  /**
   * Set the 'Accept-Encoding' header to 'gzip'
   *
   * @see #uncompress(boolean)
   * @return this request
   */
  public HttpRequest acceptGzipEncoding() {
    return acceptEncoding(ENCODING_GZIP);
  }

  /**
   * Set the 'Accept-Charset' header to given value
   *
   * @param acceptCharset
   * @return this request
   */
  public HttpRequest acceptCharset(final String acceptCharset) {
    return header(HEADER_ACCEPT_CHARSET, acceptCharset);
  }

  /**
   * Get the 'Content-Encoding' header from the response
   *
   * @return this request
   */
  public String contentEncoding() {
    return header(HEADER_CONTENT_ENCODING);
  }

  /**
   * Get the 'Server' header from the response
   *
   * @return server
   */
  public String server() {
    return header(HEADER_SERVER);
  }

  /**
   * Get the 'Date' header from the response
   *
   * @return date value, -1 on failures
   */
  public long date() {
    return dateHeader(HEADER_DATE);
  }

  /**
   * Get the 'Cache-Control' header from the response
   *
   * @return cache control
   */
  public String cacheControl() {
    return header(HEADER_CACHE_CONTROL);
  }

  /**
   * Get the 'ETag' header from the response
   *
   * @return entity tag
   */
  public String eTag() {
    return header(HEADER_ETAG);
  }

  /**
   * Get the 'Expires' header from the response
   *
   * @return expires value, -1 on failures
   */
  public long expires() {
    return dateHeader(HEADER_EXPIRES);
  }

  /**
   * Get the 'Last-Modified' header from the response
   *
   * @return last modified value, -1 on failures
   */
  public long lastModified() {
    return dateHeader(HEADER_LAST_MODIFIED);
  }

  /**
   * Get the 'Location' header from the response
   *
   * @return location
   */
  public String location() {
    return header(HEADER_LOCATION);
  }

  /**
   * Set the 'Authorization' header to given value
   *
   * @param authorization
   * @return this request
   */
  public HttpRequest authorization(final String authorization) {
    return header(HEADER_AUTHORIZATION, authorization);
  }

  /**
   * Set the 'Proxy-Authorization' header to given value
   *
   * @param proxyAuthorization
   * @return this request
   */
  public HttpRequest proxyAuthorization(final String proxyAuthorization) {
    return header(HEADER_PROXY_AUTHORIZATION, proxyAuthorization);
  }

  /**
   * Set the 'Authorization' header to given values in Basic authentication
   * format
   *
   * @param name
   * @param password
   * @return this request
   */
  public HttpRequest basic(final String name, final String password) {
    return authorization("Basic " + Base64.encode(name + ':' + password));
  }

  /**
   * Set the 'Proxy-Authorization' header to given values in Basic authentication
   * format
   *
   * @param name
   * @param password
   * @return this request
   */
  public HttpRequest proxyBasic(final String name, final String password) {
    return proxyAuthorization("Basic " + Base64.encode(name + ':' + password));
  }

  /**
   * Set the 'If-Modified-Since' request header to the given value
   *
   * @param ifModifiedSince
   * @return this request
   */
  public HttpRequest ifModifiedSince(final long ifModifiedSince) {
    getConnection().setIfModifiedSince(ifModifiedSince);
    return this;
  }

  /**
   * Set the 'If-None-Match' request header to the given value
   *
   * @param ifNoneMatch
   * @return this request
   */
  public HttpRequest ifNoneMatch(final String ifNoneMatch) {
    return header(HEADER_IF_NONE_MATCH, ifNoneMatch);
  }

  /**
   * Set the 'Content-Type' request header to the given value
   *
   * @param contentType
   * @return this request
   */
  public HttpRequest contentType(final String contentType) {
    return contentType(contentType, null);
  }

  /**
   * Set the 'Content-Type' request header to the given value and charset
   *
   * @param contentType
   * @param charset
   * @return this request
   */
  public HttpRequest contentType(final String contentType, final String charset) {
    if (charset != null && charset.length() > 0) {
      final String separator = "; " + PARAM_CHARSET + '=';
      return header(HEADER_CONTENT_TYPE, contentType + separator + charset);
    } else
      return header(HEADER_CONTENT_TYPE, contentType);
  }

  /**
   * Get the 'Content-Type' header from the response
   *
   * @return response header value
   */
  public String contentType() {
    return header(HEADER_CONTENT_TYPE);
  }

  /**
   * Get the 'Content-Length' header from the response
   *
   * @return response header value
   */
  public int contentLength() {
    return intHeader(HEADER_CONTENT_LENGTH);
  }

  /**
   * Set the 'Content-Length' request header to the given value
   *
   * @param contentLength
   * @return this request
   */
  public HttpRequest contentLength(final String contentLength) {
    return contentLength(Integer.parseInt(contentLength));
  }

  /**
   * Set the 'Content-Length' request header to the given value
   *
   * @param contentLength
   * @return this request
   */
  public HttpRequest contentLength(final int contentLength) {
    getConnection().setFixedLengthStreamingMode(contentLength);
    return this;
  }

  /**
   * Set the 'Accept' header to given value
   *
   * @param accept
   * @return this request
   */
  public HttpRequest accept(final String accept) {
    return header(HEADER_ACCEPT, accept);
  }

  /**
   * Set the 'Accept' header to 'application/json'
   *
   * @return this request
   */
  public HttpRequest acceptJson() {
    return accept(CONTENT_TYPE_JSON);
  }

  /**
   * Copy from input stream to output stream
   *
   * @param input
   * @param output
   * @return this request
   * @throws IOException
   */
  protected HttpRequest copy(final InputStream input, final OutputStream output)
      throws IOException {
    return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {

      @Override
      public HttpRequest run() throws IOException {
        final byte[] buffer = new byte[bufferSize];
        int read;
        while ((read = input.read(buffer)) != -1) {
          output.write(buffer, 0, read);
          totalWritten += read;
          progress.onUpload(totalWritten, totalSize);
        }
        return HttpRequest.this;
      }
    }.call();
  }

  /**
   * Copy from reader to writer
   *
   * @param input
   * @param output
   * @return this request
   * @throws IOException
   */
  protected HttpRequest copy(final Reader input, final Writer output)
      throws IOException {
    return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {

      @Override
      public HttpRequest run() throws IOException {
        final char[] buffer = new char[bufferSize];
        int read;
        while ((read = input.read(buffer)) != -1) {
          output.write(buffer, 0, read);
          totalWritten += read;
          progress.onUpload(totalWritten, -1);
        }
        return HttpRequest.this;
      }
    }.call();
  }

  /**
   * Set the UploadProgress callback for this request
   *
   * @param callback
   * @return this request
   */
  public HttpRequest progress(final UploadProgress callback) {
    if (callback == null)
      progress = UploadProgress.DEFAULT;
    else
      progress = callback;
    return this;
  }

  private HttpRequest incrementTotalSize(final long size) {
    if (totalSize == -1)
      totalSize = 0;
    totalSize += size;
    return this;
  }

  /**
   * Close output stream
   *
   * @return this request
   * @throws HttpRequestException
   * @throws IOException
   */
  protected HttpRequest closeOutput() throws IOException {
    progress(null);
    if (output == null)
      return this;
    if (multipart)
      output.write(CRLF + "--" + BOUNDARY + "--" + CRLF);
    if (ignoreCloseExceptions)
      try {
        output.close();
      } catch (IOException ignored) {
        // Ignored
      }
    else
      output.close();
    output = null;
    return this;
  }

  /**
   * Call {@link #closeOutput()} and re-throw a caught {@link IOException}s as
   * an {@link HttpRequestException}
   *
   * @return this request
   * @throws HttpRequestException
   */
  protected HttpRequest closeOutputQuietly() throws HttpRequestException {
    try {
      return closeOutput();
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Open output stream
   *
   * @return this request
   * @throws IOException
   */
  protected HttpRequest openOutput() throws IOException {
    if (output != null)
      return this;
    getConnection().setDoOutput(true);
    final String charset = getParam(
        getConnection().getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET);
    output = new RequestOutputStream(getConnection().getOutputStream(), charset,
        bufferSize);
    return this;
  }

  /**
   * Start part of a multipart
   *
   * @return this request
   * @throws IOException
   */
  protected HttpRequest startPart() throws IOException {
    if (!multipart) {
      multipart = true;
      contentType(CONTENT_TYPE_MULTIPART).openOutput();
      output.write("--" + BOUNDARY + CRLF);
    } else
      output.write(CRLF + "--" + BOUNDARY + CRLF);
    return this;
  }

  /**
   * Write part header
   *
   * @param name
   * @param filename
   * @return this request
   * @throws IOException
   */
  protected HttpRequest writePartHeader(final String name, final String filename)
      throws IOException {
    return writePartHeader(name, filename, null);
  }

  /**
   * Write part header
   *
   * @param name
   * @param filename
   * @param contentType
   * @return this request
   * @throws IOException
   */
  protected HttpRequest writePartHeader(final String name,
      final String filename, final String contentType) throws IOException {
    final StringBuilder partBuffer = new StringBuilder();
    partBuffer.append("form-data; name=\"").append(name);
    if (filename != null)
      partBuffer.append("\"; filename=\"").append(filename);
    partBuffer.append('"');
    partHeader("Content-Disposition", partBuffer.toString());
    if (contentType != null)
      partHeader(HEADER_CONTENT_TYPE, contentType);
    return send(CRLF);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param part
   * @return this request
   */
  public HttpRequest part(final String name, final String part) {
    return part(name, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final String part) throws HttpRequestException {
    return part(name, filename, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param contentType
   *          value of the Content-Type part header
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final String contentType, final String part) throws HttpRequestException {
    try {
      startPart();
      writePartHeader(name, filename, contentType);
      output.write(part);
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return this;
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final Number part)
      throws HttpRequestException {
    return part(name, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final Number part) throws HttpRequestException {
    return part(name, filename, part != null ? part.toString() : null);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final File part)
      throws HttpRequestException {
    return part(name, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final File part) throws HttpRequestException {
    return part(name, filename, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param contentType
   *          value of the Content-Type part header
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final String contentType, final File part) throws HttpRequestException {
    final InputStream stream;
    try {
      stream = new BufferedInputStream(new FileInputStream(part));
      incrementTotalSize(part.length());
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return part(name, filename, contentType, stream);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final InputStream part)
      throws HttpRequestException {
    return part(name, null, null, part);
  }

  /**
   * Write part of a multipart request to the request body
   *
   * @param name
   * @param filename
   * @param contentType
   *          value of the Content-Type part header
   * @param part
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest part(final String name, final String filename,
      final String contentType, final InputStream part)
      throws HttpRequestException {
    try {
      startPart();
      writePartHeader(name, filename, contentType);
      copy(part, output);
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return this;
  }

  /**
   * Write a multipart header to the response body
   *
   * @param name
   * @param value
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest partHeader(final String name, final String value)
      throws HttpRequestException {
    return send(name).send(": ").send(value).send(CRLF);
  }

  /**
   * Write contents of file to request body
   *
   * @param input
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest send(final File input) throws HttpRequestException {
    final InputStream stream;
    try {
      stream = new BufferedInputStream(new FileInputStream(input));
      incrementTotalSize(input.length());
    } catch (FileNotFoundException e) {
      throw new HttpRequestException(e);
    }
    return send(stream);
  }

  /**
   * Write byte array to request body
   *
   * @param input
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest send(final byte[] input) throws HttpRequestException {
    if (input != null)
      incrementTotalSize(input.length);
    return send(new ByteArrayInputStream(input));
  }

  /**
   * Write stream to request body
   * <p>
   * The given stream will be closed once sending completes
   *
   * @param input
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest send(final InputStream input) throws HttpRequestException {
    try {
      openOutput();
      copy(input, output);
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return this;
  }

  /**
   * Write reader to request body
   * <p>
   * The given reader will be closed once sending completes
   *
   * @param input
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest send(final Reader input) throws HttpRequestException {
    try {
      openOutput();
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    final Writer writer = new OutputStreamWriter(output,
        output.encoder.charset());
    return new FlushOperation<HttpRequest>(writer) {

      @Override
      protected HttpRequest run() throws IOException {
        return copy(input, writer);
      }
    }.call();
  }

  /**
   * Write char sequence to request body
   * <p>
   * The charset configured via {@link #contentType(String)} will be used and
   * UTF-8 will be used if it is unset.
   *
   * @param value
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest send(final CharSequence value) throws HttpRequestException {
    try {
      openOutput();
      output.write(value.toString());
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return this;
  }

  /**
   * Create writer to request output stream
   *
   * @return writer
   * @throws HttpRequestException
   */
  public OutputStreamWriter writer() throws HttpRequestException {
    try {
      openOutput();
      return new OutputStreamWriter(output, output.encoder.charset());
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

  /**
   * Write the values in the map as form data to the request body
   * <p>
   * The pairs specified will be URL-encoded in UTF-8 and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param values
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Map<?, ?> values) throws HttpRequestException {
    return form(values, CHARSET_UTF8);
  }

  /**
   * Write the key and value in the entry as form data to the request body
   * <p>
   * The pair specified will be URL-encoded in UTF-8 and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param entry
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Entry<?, ?> entry) throws HttpRequestException {
    return form(entry, CHARSET_UTF8);
  }

  /**
   * Write the key and value in the entry as form data to the request body
   * <p>
   * The pair specified will be URL-encoded and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param entry
   * @param charset
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Entry<?, ?> entry, final String charset)
      throws HttpRequestException {
    return form(entry.getKey(), entry.getValue(), charset);
  }

  /**
   * Write the name/value pair as form data to the request body
   * <p>
   * The pair specified will be URL-encoded in UTF-8 and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param name
   * @param value
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Object name, final Object value)
      throws HttpRequestException {
    return form(name, value, CHARSET_UTF8);
  }

  /**
   * Write the name/value pair as form data to the request body
   * <p>
   * The values specified will be URL-encoded and sent with the
   * 'application/x-www-form-urlencoded' content-type
   *
   * @param name
   * @param value
   * @param charset
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Object name, final Object value, String charset)
      throws HttpRequestException {
    final boolean first = !form;
    if (first) {
      contentType(CONTENT_TYPE_FORM, charset);
      form = true;
    }
    charset = getValidCharset(charset);
    try {
      openOutput();
      if (!first)
        output.write('&');
      output.write(URLEncoder.encode(name.toString(), charset));
      output.write('=');
      if (value != null)
        output.write(URLEncoder.encode(value.toString(), charset));
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
    return this;
  }

  /**
   * Write the values in the map as encoded form data to the request body
   *
   * @param values
   * @param charset
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest form(final Map<?, ?> values, final String charset)
      throws HttpRequestException {
    if (!values.isEmpty())
      for (Entry<?, ?> entry : values.entrySet())
        form(entry, charset);
    return this;
  }

  /**
   * Configure HTTPS connection to trust all certificates
   * <p>
   * This method does nothing if the current request is not a HTTPS request
   *
   * @return this request
   * @throws HttpRequestException
   */
  public HttpRequest trustAllCerts() throws HttpRequestException {
    final HttpURLConnection connection = getConnection();
    if (connection instanceof HttpsURLConnection)
      ((HttpsURLConnection) connection)
          .setSSLSocketFactory(getTrustedFactory());
    return this;
  }

  /**
   * Configure HTTPS connection to trust all hosts using a custom
   * {@link HostnameVerifier} that always returns <code>true</code> for each
   * host verified
   * <p>
   * This method does nothing if the current request is not a HTTPS request
   *
   * @return this request
   */
  public HttpRequest trustAllHosts() {
    final HttpURLConnection connection = getConnection();
    if (connection instanceof HttpsURLConnection)
      ((HttpsURLConnection) connection)
          .setHostnameVerifier(getTrustedVerifier());
    return this;
  }

  /**
   * Get the {@link URL} of this request's connection
   *
   * @return request URL
   */
  public URL url() {
    return getConnection().getURL();
  }

  /**
   * Get the HTTP method of this request
   *
   * @return method
   */
  public String method() {
    return getConnection().getRequestMethod();
  }

  /**
   * Configure an HTTP proxy on this connection. Use {{@link #proxyBasic(String, String)} if
   * this proxy requires basic authentication.
   *
   * @param proxyHost
   * @param proxyPort
   * @return this request
   */
  public HttpRequest useProxy(final String proxyHost, final int proxyPort) {
    if (connection != null)
      throw new IllegalStateException("The connection has already been created. This method must be called before reading or writing to the request.");

    this.httpProxyHost = proxyHost;
    this.httpProxyPort = proxyPort;
    return this;
  }

  /**
   * Set whether or not the underlying connection should follow redirects in
   * the response.
   *
   * @param followRedirects - true fo follow redirects, false to not.
   * @return this request
   */
  public HttpRequest followRedirects(final boolean followRedirects) {
    getConnection().setInstanceFollowRedirects(followRedirects);
    return this;
  }
}
1089829
private HttpURLConnection openConnection(URL url) throws IOException {
              HttpURLConnection connection = createConnection(url);
              connection.setUseCaches(true);
              connection.setDoInput(true);
              return connection;
       }
1225824
def connection_repo
      @options[:path] = API_REST + @options[:path]

      @options[:headers] = HEADERS.merge(AUTH_PREFIX => @final_hash[:creds]).merge(@options[:headers])

      text.msg('HTTP Request Data:')
      text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}")
      @options.each do |key, value|
        text.msg("> #{key}: #{value}")
      end
      text.msg('End HTTP Request Data.')
      if @options[:scheme] == 'https'
        @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}", @options)
      else
        Excon.defaults[:ssl_verify_peer] = false
        @connection = Excon.new("#{@options[:scheme]}://#{@options[:host]}:6001", @options)
      end
      @connection
      end
866927
void resolveUrl() throws IOException, StorageException, KeyManagementException, NoSuchAlgorithmException{
		String tempUrl;
		if(context.isCluster){
			if(this.context.lastBalancerResponse!=null){
				tempUrl = this.context.lastBalancerResponse;				
			} else {
				//System.out.println("[-] Balancer resolve! " + this.context);
				String urlString = context.url + "?appkey=" + context.applicationKey;
				URL url = new URL(urlString);
				String balancerResponse = urlString.startsWith("https:") ? secureBalancerRequest(url) : unsecureBalancerRequest(url);
				if(balancerResponse == null){
					throw new StorageException("Cannot get response from balancer!");
				}
				JSONObject obj = (JSONObject) JSONValue.parse(balancerResponse);
				tempUrl = (String)obj.get("url");
				this.context.lastBalancerResponse = tempUrl;
			}
		} else {
			tempUrl = context.url;
		}
		//tempUrl = "https://storage-ssl-prd-useast1-s0002.realtime.co:443/";
		//this.requestUrl += this.requestUrl.substring(this.requestUrl.length() - 1).equals("/") ? this.type.toString() : "/"+this.type.toString();
		tempUrl += tempUrl.substring(tempUrl.length() - 1).equals("/") ? this.type.toString() : "/"+this.type.toString();
		//path += path.substring(path.length(), 1).equals("/") ? this.type.toString() : "/"+this.type.toString();
		this.requestUrl = new URL(tempUrl);
		//System.out.println(String.format("Rest url: %s",this.requestUrl));
	}
670865
def prepare_http_connection
      conn = HTTPClient.new(options[:proxy] || self.class.proxy)
      set_http_connection_options(conn, options)
      conn
    end
670003
private String get(String urlS) throws IOException {
        URL url = new URL(urlS);
        HttpURLConnection conn = prepareAuthorizedConnection(url);
        conn.setRequestMethod("GET");
        // Read response
        StringBuilder result = new StringBuilder();
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
        }
        return result.toString();
    }
101734
public final HttpClient mapConnect(BiFunction<? super Mono<? extends Connection>, ? super Bootstrap, ? extends Mono<? extends Connection>> connector) {
		return new HttpClientOnConnectMap(this, connector);
	}
507164
public void setHTTPPort() throws InstallationFailedException {
        // Note this very significant assumption: this xpath will select exactly one connector
        Element httpConnector =
                (Element) getDocument()
                        .selectSingleNode(HTTP_CONNECTOR_XPATH);

        if (httpConnector == null) {
            throw new InstallationFailedException("Unable to set server.xml HTTP Port. XPath for Connector element failed.");
        }

        httpConnector.addAttribute("port", options
                .getValue(InstallOptions.TOMCAT_HTTP_PORT));
        httpConnector.addAttribute("enableLookups", "true"); // supports client dns/fqdn in xacml authz policies
        httpConnector.addAttribute("acceptCount", "100");
        httpConnector.addAttribute("maxThreads", "150");
        httpConnector.addAttribute("minSpareThreads", "25");
        httpConnector.addAttribute("maxSpareThreads", "75");
    }
218311
@Override
    protected void readResponse(HttpState state, HttpConnection conn)
    throws IOException, HttpException {
        LOG.trace("enter HttpMethodBase.readResponse(HttpState, HttpConnection)");
        
        boolean isUpgrade = false;
        
		while (getStatusLine() == null) {
            readStatusLine(state, conn);
            processStatusLine(state, conn);
            readResponseHeaders(state, conn);
            processResponseHeaders(state, conn);
            
            int status = this.statusLine.getStatusCode();
            if (status == 101) {
            	LOG.debug("Retrieved HTTP status code '101 Switching Protocols'. Keep connection open!");

            	// This means the requester has asked the server to switch protocols
            	// and the server is acknowledging that it will do so
            	// e.g.: upgrade to websocket
            	
				if (conn instanceof ZapHttpConnection) {
	            	isUpgrade = true;
	            	// avoid connection release of HttpClient library 
	            	conn.setHttpConnectionManager(null);
	            }
            } else if ((status >= 100) && (status < 200)) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Discarding unexpected response: " + this.statusLine.toString()); 
                }
                this.statusLine = null;
            }
        }

    	// get socket and input stream out of HttpClient
		if (conn instanceof ZapHttpConnection) {
			ZapHttpConnection zapConn = (ZapHttpConnection) conn;
	    	upgradedSocket = zapConn.getSocket();
			inputStream = zapConn.getResponseInputStream();
		}
		
		if (!isUpgrade) {
			// read & process rest of response
			// only if connection should not be kept
	        readResponseBody(state, conn);        
	        processResponseBody(state, conn);
		}
    }
624951
private static HttpURLConnection openURLConnection(URL url) throws IOException {
		// This method should be moved to a utility class in BioJava 5.0

		final int timeout = 5000;
		final String useragent = "BioJava";

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("User-Agent", useragent);
		conn.setInstanceFollowRedirects(true);
		conn.setConnectTimeout(timeout);
		conn.setReadTimeout(timeout);

		int status = conn.getResponseCode();
		while (status == HttpURLConnection.HTTP_MOVED_TEMP
				|| status == HttpURLConnection.HTTP_MOVED_PERM
				|| status == HttpURLConnection.HTTP_SEE_OTHER) {
			// Redirect!
			String newUrl = conn.getHeaderField("Location");

			if(newUrl.equals(url.toString())) {
				throw new IOException("Cyclic redirect detected at "+newUrl);
			}

			// Preserve cookies
			String cookies = conn.getHeaderField("Set-Cookie");

			// open the new connection again
			url = new URL(newUrl);
			conn.disconnect();
			conn = (HttpURLConnection) url.openConnection();
			if(cookies != null) {
				conn.setRequestProperty("Cookie", cookies);
			}
			conn.addRequestProperty("User-Agent", useragent);
			conn.setInstanceFollowRedirects(true);
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);
			conn.connect();

			status = conn.getResponseCode();

			logger.info("Redirecting from {} to {}", url, newUrl);
		}
		conn.connect();

		return conn;
	}
1108272
private static Collection<String> toHttpBalancerURIs(Collection<String> uris,
                                                      AcceptOptionsContext acceptOptionsCtx,
                                                      TransportFactory transportFactory) throws Exception {
        List<String> httpURIs = new ArrayList<>(uris.size());
        for (String uri : uris) {
            Protocol protocol = transportFactory.getProtocol(getScheme(uri));
            boolean secure = protocol.isSecure();

            for ( int i = 0; i < HTTP_TRANSPORTS.size(); i+=2) {
                String httpScheme = secure ? HTTP_TRANSPORTS.get(i) : HTTP_TRANSPORTS.get(i+1); // "httpxe+ssl" : "httpxe";
                String httpAuthority = getAuthority(uri);
                String httpPath = getPath(uri);
                String httpQuery = getQuery(uri);
                if (WsProtocol.WS.equals(protocol) || WsProtocol.WSS.equals(protocol)) {
                    httpURIs.add(buildURIAsString(httpScheme, httpAuthority,
                    URLUtils.replaceMultipleSlashesWithSingleSlash(httpPath + WsebAcceptor.EMULATED_SUFFIX), httpQuery, null));

                    // ensure that the accept-options is updated with bindings if they exist for ws and/or wss
                    // so that the Gateway binds to the correct host:port as per the service configuration.
                    String internalURI = acceptOptionsCtx.getInternalURI(uri);
                    if ((internalURI != null) && !internalURI.equals(uri)) {
                        String authority = getAuthority(internalURI);
                        acceptOptionsCtx.addBind(httpScheme, authority);
                    }
                }
                else if (SseProtocol.SSE.equals(protocol) || SseProtocol.SSE_SSL.equals(protocol) ||
                         HttpProtocol.HTTP.equals(protocol) || HttpProtocol.HTTPS.equals(protocol)) {
                    httpURIs.add(buildURIAsString(httpScheme, httpAuthority, httpPath, httpQuery, null));
                }
                else {
                    // we do not balance anything other than http, ws and sse
                    throw new IllegalArgumentException("Invalid protocol in the balancer: " + uri);
                }
            }
        }
        return httpURIs;
    }
1366647
def InitHttp(api_endpoint=None,
             page_size=None,
             auth=None,
             proxies=None,
             verify=None,
             cert=None,
             trust_env=True):
  """"""

  connector = http_connector.HttpConnector(
      api_endpoint=api_endpoint,
      page_size=page_size,
      auth=auth,
      proxies=proxies,
      verify=verify,
      cert=cert,
      trust_env=trust_env)

  return GrrApi(connector=connector)
1356792
def _get_connection(self, uri, headers=None):
    
    connection = None
    if uri.scheme == 'https':
      if not uri.port:
        connection = httplib.HTTPSConnection(uri.host)
      else:
        connection = httplib.HTTPSConnection(uri.host, int(uri.port))
    else:
      if not uri.port:
        connection = httplib.HTTPConnection(uri.host)
      else:
        connection = httplib.HTTPConnection(uri.host, int(uri.port))
    return connection
843383
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {
          URI uri = request.getURI();

          // Is this a CONNECT request?
          if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) {
              response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
              handleConnect(pathInContext, pathParams, request, response);
              return;
          }

          try {

              // Has the requested resource been found?
              if ("True".equals(response.getAttribute("NotFound"))) {
                  response.removeAttribute("NotFound");
                  sendNotFound(response);
                  return;
              }

              // Do we proxy this?
              URL url = isProxied(uri);
              if (url == null) {
                  if (isForbidden(uri))
                      sendForbid(request, response, uri);
                  return;
              }

              // is this URL a /selenium URL?
              if (isSeleniumUrl(url.toString())) {
                  request.setHandled(false);
                  return;
              }

              proxyPlainTextRequest(url, pathInContext, pathParams, request, response);
          }
          catch (UnknownHostException e){
            log.info("Couldn't proxy to " + uri + " because host not found");
            response.setStatus(400);
            String host = uri.getHost();
            response.setReason("Host " + host + " not found");
            OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
            out.write("<html>" +
                "<head><title>Problem loading page</title></head>" +
                "<body style=\"background-color:#F0F0F0; font-family: sans-serif\">" +
                "<div style=\"margin:auto; margin-top: 3em;width:600px; background-color:#FFF; padding:30px;border: 1px solid #DDD\">" +
                "<h1 style=\"font-size: 18px;border-bottom:thin solid #DDD\">Server not found</h1>" +
                "<p style=\"border-bottom: 1px solid #DDD; padding-bottom: 20px\">Selenium can't find the server at "+host+"</p>" +
                "<ul style=\"list-style: square outside none;font-size:13px\">" +
                "<li style=\"margin-bottom:6px;\">Check the address for typing errors such as ww.example.com instead of www.example.com</li>" +
                "<li style=\"margin-bottom:6px;\">If you are unable to load any pages, check your computer's network connection.</li>" +
                "<li style=\"margin-bottom:6px;\">If your computer or network is protected by a firewall or proxy, make sure that your browser is permitted to access the Web.</li>" +
                "</ul>" +
                "</div>" +
                "</body>");
            out.close();
            response.getOutputStream().close();
          }
          catch (ConnectException e){
            log.info("Couldn't proxy to " + uri + " because host not listening");
            response.setStatus(400);
            String host = uri.getHost();
            if(uri.getPort() > 0){
                host = host + ":" + uri.getPort();
            }
            response.setReason("Couldn't connect to " + host);
            OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
            out.write("<html>" +
                "<head><title>Problem loading page</title></head>" +
                "<body style=\"background-color:#F0F0F0; font-family: sans-serif\">" +
                "<div style=\"margin:auto; margin-top: 3em;width:600px; background-color:#FFF; padding:30px;border: 1px solid #DDD\">" +
                "<h1 style=\"font-size: 18px;border-bottom:thin solid #DDD\">Unable to connect</h1>" +
                "<p style=\"border-bottom: 1px solid #DDD; padding-bottom: 20px\">Selenium can't establish a connection to the server at "+host+"</p>" +
                "<ul style=\"list-style: square outside none;font-size:13px\">" +
                "<li style=\"margin-bottom:6px;\">The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
                "<li style=\"margin-bottom:6px;\">If you are unable to load any pages, check your computer's network connection.</li>" +
                "<li style=\"margin-bottom:6px;\">If your computer or network is protected by a firewall or proxy, make sure that your browser is permitted to access the Web.</li>" +
                "</ul>" +
                "</div>" +
                "</body>");

            out.close();
            response.getOutputStream().close();
          }
          catch (Exception e) {
              log.log(Level.FINE, "Could not proxy " + uri, e);
              if (!response.isCommitted())
                  response.sendError(HttpResponse.__400_Bad_Request, "Could not proxy " + uri + "\n" + e);
          }
      }