Handle a single HTTP GET request.

        Default implementation indicates an error because
        XML-RPC uses the POST method.
776968
def handle_get(self):
        

        code = 400
        message, explain = \
                 BaseHTTPServer.BaseHTTPRequestHandler.responses[code]

        response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % { #@UndefinedVariable
             'code' : code,
             'message' : message,
             'explain' : explain
            }
        sys.stdout.write('Status: %d %s\n' % (code, message))
        sys.stdout.write('Content-Type: text/html\n')
        sys.stdout.write('Content-Length: %d\n' % len(response))
        sys.stdout.write('\n')

        sys.stdout.write(response)
653095
def request(self, url, method = u"get", data = None, headers = None, **kwargs):
        

        url, method, data, headers, kwargs = self._pre_request(url, 
                                                                 method=method,
                                                                 data=data,
                                                                 headers=headers,
                                                                 **kwargs)
        response = self._request(url, method=method, data=data, headers=headers, **kwargs)
        response = self._post_request(response)
        
        # raises the appropriate exceptions
        response = self._handle_response(response)
        
        return response
964876
def do_POST(self, request, response):
        # pylint: disable=C0103
        
        # Get the request JSON content
        data = jsonrpclib.loads(to_str(request.read_data()))

        # Convert from Jabsorb
        data = jabsorb.from_jabsorb(data)

        # Dispatch
        try:
            result = self._unmarshaled_dispatch(data, self._simple_dispatch)
        except NoMulticallResult:
            # No result (never happens, but who knows...)
            result = None

        if result is not None:
            # Convert result to Jabsorb
            if "result" in result:
                result["result"] = jabsorb.to_jabsorb(result["result"])

            # Store JSON
            result = jsonrpclib.jdumps(result)
        else:
            # It was a notification
            result = ""

        # Send the result
        response.send_content(200, result, "application/json-rpc")
1311822
@Override
    public void handle(Response<ByteSource> rs) throws RestEndpointIOException {
        if (!hasError(rs)) {
            return;
        }

        handleError(rs.getUri(), rs.getHttpMethod(), rs.getStatus(), rs.getReason(), rs.getBody());

    }
871852
def post(self, param, h, r):
        '''
        
        '''
        try:
            rsp = self.client().post(self.uri(), param)
            # print(rsp)
            return self.result(rsp, h, r)
        except ValueError as err:
            return h.catch_exception(err, r)
798664
def handle_exception(self, e, request=None):
        
        if isinstance(e, HttpError):
            response = SerializedHttpResponse(e.content, status=e.status)
            return self.emit(
                response, request=request, emitter=e.emitter)

        if isinstance(e, (AssertionError, ValidationError)):

            content = unicode(e)

            if isinstance(e, FormError):
                content = e.form.errors

            response = SerializedHttpResponse(
                content, status=status.HTTP_400_BAD_REQUEST)

            return self.emit(response, request=request)

        if ADREST_DEBUG:
            raise

        logger.exception('\nADREST API Error: %s', request.path)

        return HttpResponse(str(e), status=500)
773048
public void handleGet(HttpRequest request,
                          HttpResponse response,
                          String pathInContext,
                          String pathParams,
                          Resource resource)
        throws IOException
    {
        if(log.isDebugEnabled())log.debug("Looking for "+resource);
        
        if (resource!=null && resource.exists())
        {            
            // check if directory
            if (resource.isDirectory())
            {
                if (!pathInContext.endsWith("/") && !pathInContext.equals("/"))
                {
                    log.debug("Redirect to directory/");
                    
                    String q=request.getQuery();
                    StringBuffer buf=request.getRequestURL();
                    if (q!=null&&q.length()!=0)
                    {
                        buf.append('?');
                        buf.append(q);
                    }
                    response.setField(HttpFields.__Location, URI.addPaths(buf.toString(),"/"));
                    response.setStatus(302);
                    request.setHandled(true);
                    return;
                }
  
                // See if index file exists
                String welcome=getHttpContext().getWelcomeFile(resource);
                if (welcome!=null)
                {     
                    // Forward to the index
                    String ipath=URI.addPaths(pathInContext,welcome);
                    if (_redirectWelcomeFiles)
                    {
                        // Redirect to the index
                        ipath=URI.addPaths(getHttpContext().getContextPath(),ipath);
                        response.setContentLength(0);
                        response.sendRedirect(ipath);
                    }
                    else
                    {
                        URI uri=request.getURI();
                        uri.setPath(URI.addPaths(uri.getPath(),welcome));
                        getHttpContext().handle(ipath,pathParams,request,response);
                    }
                    return;
                }

                // Check modified dates
                if (!passConditionalHeaders(request,response,resource))
                    return;
                // If we got here, no forward to index took place
                sendDirectory(request,response,resource,pathInContext.length()>1);
            }
            // check if it is a file
            else if (resource.exists())
            {
                // Check modified dates
                if (!passConditionalHeaders(request,response,resource))
                    return;
                sendData(request,response,pathInContext,resource,true);
            }
            else
                // don't know what it is
                log.warn("Unknown file type");
        }
    }
642887
def handle_one_request(self):
        """"""
        self.raw_requestline = self.rfile.readline()
        if not self.raw_requestline:
            self.close_connection = 1
        elif self.parse_request():
            return self.run_wsgi()
708463
def do_POST(self):
        

        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).
            max_chunk_size = 10 * 1024 * 1024
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                L.append(self.rfile.read(chunk_size))
                size_remaining -= len(L[-1])
            data = ''.join(L)

            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
                )
        except: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)
            self.end_headers()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)

            # shut down the connection
            self.wfile.flush()
            self.connection.shutdown(1)
346328
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        if (!isStarted())
            return;
        
        // Only handle GET, HEAD and POST
        if (!HttpRequest.__GET.equals(request.getMethod()) &&
            !HttpRequest.__HEAD.equals(request.getMethod()) &&
            !HttpRequest.__POST.equals(request.getMethod()))
            return;

        log.debug("Dump");
        
        response.setField(HttpFields.__ContentType,
                          HttpFields.__TextHtml);
        OutputStream out = response.getOutputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
        Writer writer = new OutputStreamWriter(buf,StringUtil.__ISO_8859_1);
        writer.write("<HTML><H1>Dump HttpHandler</H1>");
        writer.write("<PRE>\npath="+request.getPath()+
                    "\ncontextPath="+getHttpContext().getContextPath()+
                    "\npathInContext="+pathInContext+
                    "\n</PRE>\n");
        writer.write("<H3>Header:</H3><PRE>");
        writer.write(request.toString());
        writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
        Set names=request.getParameterNames();
        Iterator iter = names.iterator();
        while(iter.hasNext())
        {
            String name=iter.next().toString();
            List values=request.getParameterValues(name);
            if (values==null || values.size()==0)
            {
                writer.write(name);
                writer.write("=\n");
            }
            else if (values.size()==1)
            {
                writer.write(name);
                writer.write("=");
                writer.write((String)values.get(0));
                writer.write("\n");
            }
            else
            {
                for (int i=0; i<values.size(); i++)
                {
                    writer.write(name);
                    writer.write("["+i+"]=");
                    writer.write((String)values.get(i));
                    writer.write("\n");
                }
            }
        }
        
        String cookie_name=request.getParameter("CookieName");
        if (cookie_name!=null && cookie_name.trim().length()>0)
        {
            String cookie_action=request.getParameter("Button");
            try{
                Cookie cookie=
                    new Cookie(cookie_name.trim(),
                               request.getParameter("CookieVal"));
                if ("Clear Cookie".equals(cookie_action))
                    cookie.setMaxAge(0);
                response.addSetCookie(cookie);
            }
            catch(IllegalArgumentException e)
            {
                writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
                writer.write(e.toString());
                LogSupport.ignore(log,e);
            }
        }
        
        writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
        Cookie[] cookies=request.getCookies();
        if (cookies!=null && cookies.length>0)
        {
            for(int c=0;c<cookies.length;c++)
            {
                Cookie cookie=cookies[c];
                writer.write(cookie.getName());
                writer.write("=");
                writer.write(cookie.getValue());
                writer.write("\n");
            }
        }
        
        writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
        Enumeration attributes=request.getAttributeNames();
        if (attributes!=null && attributes.hasMoreElements())
        {
            while(attributes.hasMoreElements())
            {
                String attr=attributes.nextElement().toString();
                writer.write(attr);
                writer.write("=");
                writer.write(request.getAttribute(attr).toString());
                writer.write("\n");
            }
        }
        
        writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
        byte[] content= new byte[4096];
        int len;
        try{
            InputStream in=request.getInputStream();
            while((len=in.read(content))>=0)
                writer.write(new String(content,0,len));
        }
        catch(IOException e)
        {
            LogSupport.ignore(log,e);
            writer.write(e.toString());
        }
        
        // You wouldn't normally set a trailer like this, but
        // we don't want to commit the output to force trailers as
        // it makes test harness messy
        request.getAcceptableTransferCodings();
        
        // commit now
        writer.flush();
        response.setIntField(HttpFields.__ContentLength,buf.size()+1000);
        buf.writeTo(out);
        out.flush();
        
        // Now add the response
        buf.reset();
        writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
        writer.write(response.toString());
        writer.write("</PRE></HTML>");
        writer.flush();
        for (int pad=998-buf.size();pad-->0;)
            writer.write(" ");
        writer.write("\015\012");
        writer.flush();
        buf.writeTo(out);
            
        request.setHandled(true);
    }
228330
def _http_request(url,
                  method='GET',
                  headers=None,
                  data=None):
    '''
    
    '''
    req = requests.request(method,
                           url,
                           headers=headers,
                           data=data)
    ret = _default_ret()
    ok_status = METHOD_OK_STATUS.get(method, 200)
    if req.status_code != ok_status:
        ret.update({
            'comment': req.json().get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json() if method != 'DELETE' else None  # no body when DELETE
    })
    return ret
862395
def _handle_post(self, method, remainder, request=None):
        '''
        
        '''
        if request is None:
            self._raise_method_deprecation_warning(self._handle_post)

        # check for custom POST/PUT requests
        if remainder:
            match = self._handle_custom_action(method, remainder, request)
            if match:
                return match

            controller = self._lookup_child(remainder[0])
            if controller and not ismethod(controller):
                return lookup_controller(controller, remainder[1:], request)

        # check for regular POST/PUT requests
        controller = self._find_controller(method)
        if controller:
            return controller, remainder

        abort(405)
1128285
private ExecuteResult execute(HttpConnection connection) {

        InputStream inputStream = null; // input stream - response from server on success
        InputStream errorStream = null; // error stream - response from server for a 500 etc
        String responseMessage = null;
        int responseCode = -1;
        Throwable cause = null;

        // first try to execute our request and get the input stream with the server's response
        // we want to catch IOException because HttpUrlConnection throws these for non-success
        // responses (eg 404 throws a FileNotFoundException) but we need to map to our own
        // specific exceptions
        try {
            inputStream = connection.execute().responseAsInputStream();
        } catch (IOException ioe) {
            cause = ioe;
        }

        // response code and message will generally be present together or not all
        try {
            responseCode = connection.getConnection().getResponseCode();
            responseMessage = connection.getConnection().getResponseMessage();
        } catch (IOException ioe) {
            responseMessage = "Error retrieving server response message";
        }

        // error stream will be present or null if not applicable
        errorStream = connection.getConnection().getErrorStream();

        try {
            ExecuteResult executeResult = new ExecuteResult(inputStream,
                    errorStream,
                    responseCode,
                    responseMessage,
                    cause
            );
            return executeResult;
        } finally {
            // don't close inputStream as the callee still needs it
            IOUtils.closeQuietly(errorStream);
        }
    }
725154
def handle_request(self, request_text=None):
        

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            if request_text is None:
                request_text = sys.stdin.read()

            self.handle_xmlrpc(request_text)
977373
def __request(self, method, url, request_args, headers=None, stream=False):
        
        func = getattr(self.client, method)
        headers = headers if headers else {}
        response = None
        try:
            logger.info("performing request %s", url)
            response = func(url, stream=stream, headers=headers,
                            **request_args)
        except requests.RequestException as err:
            logger.error("request %s failed [%s]", url, err)
            raise err

        # Handle error responses
        if response.status_code >= 400:
            logger.error("request %s failed [%d,%s]",
                         url,
                         response.status_code,
                         response.content.decode('utf-8'))
            raise V20Error(response.status_code,
                           response.content.decode('utf-8'))
        return response
1255261
def _handle_response(response, **kwargs) -> XMLResponse:
        
        if not response.encoding:
            response.encoding = DEFAULT_ENCODING

        return response
16336
static HttpResponse executeRequest(ProtocolCommand command, String mimeType) {
    HttpClient client = ((ProtocolConnection)command.getConnection()).getHttpClient();
    URL url = ((ProtocolDataSource)command.getConnection().getDataSource()).getUrl();
    HttpUriRequest req;

    try {
      String params = "query=" + encode(command.getCommand());
      String u = url.toString() + "?" + params;
      if (u.length() > QUERY_LIMIT) {
        // POST connection
        try {
          req = new HttpPost(url.toURI());
        } catch (URISyntaxException e) {
          throw new SparqlException("Endpoint <" + url + "> not in an acceptable format", e);
        }
        ((HttpPost) req).setEntity((HttpEntity) new StringEntity(params));
      } else {
        // GET connection
        req = new HttpGet(u);
      }

      if (command.getTimeout() != Command.NO_TIMEOUT) {
        HttpParams reqParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(reqParams, (int) (command.getTimeout() * 1000));
        req.setParams(reqParams);
      }
      
      // Add Accept and Content-Type (for POST'ed queries) headers to the request.
      addHeaders(req, mimeType);
      
      // There's a small chance the request could be aborted before it's even executed, we'll have to live with that.
      command.setRequest(req);
      
      //dump(client, req);
      HttpResponse response = client.execute(req);
      StatusLine status = response.getStatusLine();
      int code = status.getStatusCode();
      
      // TODO the client doesn't handle redirects for posts; should we do that here?

      if (code >= SUCCESS_MIN && code <= SUCCESS_MAX) {
        return response;
      } else {
        throw new SparqlException("Unexpected status code in server response: " +
            status.getReasonPhrase() + "(" + code + ")");
      }
    } catch (UnsupportedEncodingException e) {
      throw new SparqlException("Unabled to encode data", e);
    } catch (ClientProtocolException cpe) {
      throw new SparqlException("Error in protocol", cpe);
    } catch (IOException e) {
      throw new SparqlException(e);
    }
  }