Sends a MKCOL request to the +path+ and gets a response,
 as an HTTPResponse object.
556541
def mkcol(path, body = nil, initheader = nil)
      request(Mkcol.new(path, initheader), body)
    end
912639
public static HttpResponse doGetResponse(String host, String path,
                                             Map<String, String> headers,
                                             Map<String, String> queries) throws Exception {
        HttpClient httpClient = wrapClient(host);
        if (queries == null)
            queries = new HashMap<>();

        HttpGet request = new HttpGet(buildUrl(host, path, queries));

        if (headers == null) {
            headers = new HashMap<>();
            setHttpHeader(request);
        }

        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }
1087072
def _call(self, method, path, data=None):
    
    if is_python3():
      conn = http.client.HTTPConnection(API_HOST)
    else:
      conn = httplib.HTTPConnection(API_HOST)

    headers = {'User-Agent' : USER_AGENT}

    if data:
      headers.update( {'Content-type': 'application/x-www-form-urlencoded'} )
      conn.request(method, path, self._urlencode(data), headers)

    else:
      conn.request(method, path, None, headers)

    response = conn.getresponse()
    result   =  [response.status, self._parse_body(response.read())]
    conn.close()
    return result
605478
def request(method, path, options, &block)
      response = connection(options).send(method) do |request|
        block.call(request) if block_given?
        request.url(path)
      end
      response.body
    end
1143433
def post(self, path, valuemap=None, query=None):
        
        self.lastpath = path
        if query is not None:
            self.lastpath += '?' + urlencode(query)
        if valuemap:
            self.http.request('POST', self.lastpath, urlencode(valuemap),
                                {"Content-type": "application/x-www-form-urlencoded"})
        else:
            self.http.request('POST', self.lastpath, '')
        resp = self.http.getresponse()
        ctype = resp.getheader('Content-Type')
        data = resp.read().decode('utf-8')
        self.log.debug("Request '%s' status %d, %s length %d", self.lastpath, resp.status, ctype, len(data))
        if resp.status < 400:
            return (resp.status, data, ctype)
        else:
            raise HttpError(code=resp.status, content_type=ctype, content=data)
446541
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
		throws IOException, ParseException {

		// make sure we request the "index.html" in case there is a directory request
		if (requestPath.endsWith("/")) {
			requestPath = requestPath + "index.html";
		}

		if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js
			requestPath = requestPath + ".json";
		}

		// convert to absolute path
		final File file = new File(rootPath, requestPath);

		if (!file.exists()) {
			// file does not exist. Try to load it with the classloader
			ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();

			try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
				boolean success = false;
				try {
					if (resourceStream != null) {
						URL root = cl.getResource("web");
						URL requested = cl.getResource("web" + requestPath);

						if (root != null && requested != null) {
							URI rootURI = new URI(root.getPath()).normalize();
							URI requestedURI = new URI(requested.getPath()).normalize();

							// Check that we don't load anything from outside of the
							// expected scope.
							if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
								LOG.debug("Loading missing file from classloader: {}", requestPath);
								// ensure that directory to file exists.
								file.getParentFile().mkdirs();
								Files.copy(resourceStream, file.toPath());

								success = true;
							}
						}
					}
				} catch (Throwable t) {
					LOG.error("error while responding", t);
				} finally {
					if (!success) {
						LOG.debug("Unable to load requested file {} from classloader", requestPath);
						HandlerUtils.sendErrorResponse(
							ctx,
							request,
							new ErrorResponseBody("File not found."),
							NOT_FOUND,
							Collections.emptyMap());
						return;
					}
				}
			}
		}

		if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		// cache validation
		final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
		if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
			SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
			Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

			// Only compare up to the second because the datetime format we send to the client
			// does not have milliseconds
			long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
			long fileLastModifiedSeconds = file.lastModified() / 1000;
			if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
				}

				StaticFileServerHandler.sendNotModified(ctx);
				return;
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
		}

		// Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
		final RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(file, "r");
		} catch (FileNotFoundException e) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		try {
			long fileLength = raf.length();

			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			StaticFileServerHandler.setContentTypeHeader(response, file);

			// the job overview should be updated as soon as possible
			if (!requestPath.equals("/joboverview.json")) {
				StaticFileServerHandler.setDateAndCacheHeaders(response, file);
			}
			if (HttpHeaders.isKeepAlive(request)) {
				response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			HttpHeaders.setContentLength(response, fileLength);

			// write the initial line and the header.
			ctx.write(response);

			// write the content.
			ChannelFuture lastContentFuture;
			if (ctx.pipeline().get(SslHandler.class) == null) {
				ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
				lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			} else {
				lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
					ctx.newProgressivePromise());
				// HttpChunkedInput will write the end marker (LastHttpContent) for us.
			}

			// close the connection, if no keep-alive is needed
			if (!HttpHeaders.isKeepAlive(request)) {
				lastContentFuture.addListener(ChannelFutureListener.CLOSE);
			}
		} catch (Exception e) {
			raf.close();
			LOG.error("Failed to serve file.", e);
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("Internal server error."),
				INTERNAL_SERVER_ERROR,
				Collections.emptyMap());
		}
	}
584364
def request(method, path, options, raw=false, unformatted=true)
      response = connection(raw).send(method) do |request|
        path = formatted_path(path) unless unformatted
        case method
        when :get, :delete
          request.url(path, options)
        when :post, :put
          request.path = path
          request.body = options unless options.empty?
        end
      end
      raw ? response : response.body
    end
222329
def get_response(self, request):
        ''''''
        # the redirect key is already placed in the response by HttpResponseJavascriptRedirect
        return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, **self.kwargs)
965590
public void sendData(HttpRequest request,
                         HttpResponse response,
                         String pathInContext,
                         Resource resource,
                         boolean writeHeaders)
        throws IOException
    {
        long resLength=resource.length();
        
        //  see if there are any range headers
        Enumeration reqRanges =
            request.getDotVersion()>0
            ?request.getFieldValues(HttpFields.__Range)
            :null;
        
        if (!writeHeaders || reqRanges == null || !reqRanges.hasMoreElements())
        {
            // look for a gziped content.
            Resource data=resource;
            if (_minGzipLength>0)
            {
                String accept=request.getField(HttpFields.__AcceptEncoding);
                if (accept!=null && resLength>_minGzipLength &&
                    !pathInContext.endsWith(".gz"))
                {
                    Resource gz = getHttpContext().getResource(pathInContext+".gz");
                    if (gz.exists() && accept.indexOf("gzip")>=0)
                    {
                        if(log.isDebugEnabled())log.debug("gzip="+gz);
                        response.setField(HttpFields.__ContentEncoding,"gzip");
                        data=gz;
                        resLength=data.length();
                    }
                }
            }
            writeHeaders(response,resource,resLength);
            
            request.setHandled(true);
            OutputStream out = response.getOutputStream();
            data.writeTo(out,0,resLength);
            return;
        }
            
        // Parse the satisfiable ranges
        List ranges =InclusiveByteRange.satisfiableRanges(reqRanges,resLength);
        if(log.isDebugEnabled())log.debug("ranges: " + reqRanges + " == " + ranges);
        
        //  if there are no satisfiable ranges, send 416 response
        if (ranges==null || ranges.size()==0)
        {
            log.debug("no satisfiable ranges");
            writeHeaders(response, resource, resLength);
            response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable);
            response.setReason((String)HttpResponse.__statusMsg
                               .get(TypeUtil.newInteger(HttpResponse.__416_Requested_Range_Not_Satisfiable)));

            response.setField(HttpFields.__ContentRange, 
                              InclusiveByteRange.to416HeaderRangeString(resLength));
            
            OutputStream out = response.getOutputStream();
            resource.writeTo(out,0,resLength);
            request.setHandled(true);
            return;
        }

        
        //  if there is only a single valid range (must be satisfiable 
        //  since were here now), send that range with a 216 response
        if ( ranges.size()== 1)
        {
            InclusiveByteRange singleSatisfiableRange =
                (InclusiveByteRange)ranges.get(0);
            if(log.isDebugEnabled())log.debug("single satisfiable range: " + singleSatisfiableRange);
            long singleLength = singleSatisfiableRange.getSize(resLength);
            writeHeaders(response,resource,singleLength);
            response.setStatus(HttpResponse.__206_Partial_Content);
            response.setReason((String)HttpResponse.__statusMsg
                               .get(TypeUtil.newInteger(HttpResponse.__206_Partial_Content)));
            response.setField(HttpFields.__ContentRange, 
                              singleSatisfiableRange.toHeaderRangeString(resLength));
            OutputStream out = response.getOutputStream();
            resource.writeTo(out,
                             singleSatisfiableRange.getFirst(resLength), 
                             singleLength);
            request.setHandled(true);
            return;
        }

        
        //  multiple non-overlapping valid ranges cause a multipart
        //  216 response which does not require an overall 
        //  content-length header
        //
        ResourceCache.ResourceMetaData metaData =
            (ResourceCache.ResourceMetaData)resource.getAssociate();
        String encoding = metaData.getMimeType();
        MultiPartResponse multi = new MultiPartResponse(response);
        response.setStatus(HttpResponse.__206_Partial_Content);
        response.setReason((String)HttpResponse.__statusMsg
                           .get(TypeUtil.newInteger(HttpResponse.__206_Partial_Content)));

	// If the request has a "Request-Range" header then we need to
	// send an old style multipart/x-byteranges Content-Type. This
	// keeps Netscape and acrobat happy. This is what Apache does.
	String ctp;
	if (request.containsField(HttpFields.__RequestRange))
	    ctp = "multipart/x-byteranges; boundary=";
	else
	    ctp = "multipart/byteranges; boundary=";
	response.setContentType(ctp+multi.getBoundary());

        InputStream in=(resource instanceof CachedResource)
            ?null:resource.getInputStream();
        OutputStream out = response.getOutputStream();
        long pos=0;
            
        for (int i=0;i<ranges.size();i++)
        {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            String header=HttpFields.__ContentRange+": "+
                ibr.toHeaderRangeString(resLength);
            if(log.isDebugEnabled())log.debug("multi range: "+encoding+" "+header);
            multi.startPart(encoding,new String[]{header});

            long start=ibr.getFirst(resLength);
            long size=ibr.getSize(resLength);
            if (in!=null)
            {
                // Handle non cached resource
                if (start<pos)
                {
                    in.close();
                    in=resource.getInputStream();
                    pos=0;
                }
                if (pos<start)
                {
                    in.skip(start-pos);
                    pos=start;
                }
                IO.copy(in,out,size);
                pos+=size;
            }
            else
                // Handle cached resource
                resource.writeTo(out,start,size);
            
        }
        if (in!=null)
            in.close();
        multi.close();

        request.setHandled(true);

        return;
    }
21980
def request(method, path)
        resource[path].send(method.to_sym, request_headers) { |response, request, result, &block|
          case response.code
            when 200
              response
            when 400
              if response.include? ' is required'
                raise ArgumentError.new(response)
              else
                raise BadRequestError.new(response)
              end
            else
              response.return!(request, result, &block)
          end
        }
      end
171430
def mkdir(path)
      path = @uri.merge(path).path
      res = @handler.request(:mkcol, path, nil, @headers)
      res.body
    end
511157
def post(path, options={}, raw=false, unformatted=true)
      request(:post, path, options, raw, unformatted)
    end
1215484
def _request(self, path, method, body=None):
        """"""
        url = '/'.join([_SERVER, path])
        (resp, content) = _HTTP.request(url, method,
                                        headers=self._headers, body=body)

        content_type = resp.get('content-type')
        if content_type and content_type.startswith('application/json'):
            content = json.loads(content.decode('UTF-8'))

        return (resp, content)
854495
def request(http_method, path, params)
      response = connection.send(http_method, path, params)
      response.body
    end
216149
def request(self, path, method='GET', params=None, type=REST_TYPE):
        """"""
        response_text = self._get_http_client(type).request(path, method, params)

        if not response_text:
            return response_text

        response_json = json.loads(response_text)

        if 'errors' in response_json:
            raise (ErrorException([Error().load(e) for e in response_json['errors']]))

        return response_json
574166
public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException
    {
        URL url = null;
        try {
            url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader());
        } catch (RuntimeException e) {
            e.printStackTrace();    // ???
        }        	
        if (url == null)
            return false;   // Not found
        InputStream inStream = null;
        try {
            inStream = url.openStream();
        } catch (Exception e) {
            return false;   // Not found
        }

        // Todo may want to add cache info (using bundle lastModified).
        OutputStream writer = response.getOutputStream();
        if (response.getContentType() == null)
        {
            if (httpContext != null)
                response.setContentType(httpContext.getMimeType(path));
            else
            	response.setContentType(FileHttpContext.getDefaultMimeType(path));
        }
        copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things
        writer.close();
        inStream.close();
        return true;
    }
301610
def post_query(path, data = {})
      @request_uri = "#{@base_uri}#{path}" 
      body = URI.encode_www_form(data)
      extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' }
      req  = post_request(path, body, extheader)
      @res = http_connection.start {|http| http.request(req) }
      handle_error(@res, @request_uri)
      JSON.parse(@res.body)
    end