Example usage for org.apache.http.client.methods HttpTrace HttpTrace

List of usage examples for org.apache.http.client.methods HttpTrace HttpTrace

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpTrace HttpTrace.

Prototype

public HttpTrace(final String uri) 

Source Link

Usage

From source file:org.apache.nutch.protocol.httpclient.HttpClientRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {//from   ww w . j  a  v a 2 s .  c o  m
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                return copyEntity(new HttpPost(uri), request);
            } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
                return copyEntity(new HttpPut(uri), request);
            } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
                return new HttpDelete(uri);
            } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
                return new HttpTrace(uri);
            } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
                return new HttpOptions(uri);
            } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
                return copyEntity(new HttpPatch(uri), request);
            }
        }
        return new HttpGet(uri);
    }
}

From source file:org.rapidoid.http.HttpClient.java

public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback,
        boolean fullResponse) {

    headers = U.safe(headers);//from  w ww.ja v  a 2s.co m
    data = U.safe(data);
    files = U.safe(files);

    HttpRequestBase req;
    boolean canHaveBody = false;

    if ("GET".equalsIgnoreCase(verb)) {
        req = new HttpGet(uri);
    } else if ("DELETE".equalsIgnoreCase(verb)) {
        req = new HttpDelete(uri);
    } else if ("OPTIONS".equalsIgnoreCase(verb)) {
        req = new HttpOptions(uri);
    } else if ("HEAD".equalsIgnoreCase(verb)) {
        req = new HttpHead(uri);
    } else if ("TRACE".equalsIgnoreCase(verb)) {
        req = new HttpTrace(uri);
    } else if ("POST".equalsIgnoreCase(verb)) {
        req = new HttpPost(uri);
        canHaveBody = true;
    } else if ("PUT".equalsIgnoreCase(verb)) {
        req = new HttpPut(uri);
        canHaveBody = true;
    } else if ("PATCH".equalsIgnoreCase(verb)) {
        req = new HttpPatch(uri);
        canHaveBody = true;
    } else {
        throw U.illegalArg("Illegal HTTP verb: " + verb);
    }

    for (Entry<String, String> e : headers.entrySet()) {
        req.addHeader(e.getKey(), e.getValue());
    }

    if (canHaveBody) {
        HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

        if (body != null) {

            NByteArrayEntity entity = new NByteArrayEntity(body);

            if (contentType != null) {
                entity.setContentType(contentType);
            }

            entityEnclosingReq.setEntity(entity);
        } else {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (Entry<String, String> entry : files.entrySet()) {
                String filename = entry.getValue();
                File file = IO.file(filename);
                builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
            }

            for (Entry<String, String> entry : data.entrySet()) {
                builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                builder.build().writeTo(stream);
            } catch (IOException e) {
                throw U.rte(e);
            }

            byte[] bytes = stream.toByteArray();
            NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);

            entityEnclosingReq.setEntity(entity);
        }
    }

    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    return execute(client, req, callback, fullResponse);
}

From source file:org.springframework.http.client.HttpComponentsClientHttpRequestFactory.java

/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 *
 * @param httpMethod the HTTP method/*from w w  w.  j a  va2  s  . c  o m*/
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
    switch (httpMethod) {
    case GET:
        return new HttpGet(uri);
    case DELETE:
        return new HttpDelete(uri);
    case HEAD:
        return new HttpHead(uri);
    case OPTIONS:
        return new HttpOptions(uri);
    case POST:
        return new HttpPost(uri);
    case PUT:
        return new HttpPut(uri);
    case TRACE:
        return new HttpTrace(uri);
    default:
        throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}

From source file:ru.histone.resourceloaders.DefaultResourceLoader.java

private StreamResource loadHttpResource(URI location, Node[] args) {
    URI newLocation = URI.create(location.toString().replace("#fragment", ""));
    final Map<Object, Node> requestMap = args != null && args.length != 0
            && args[0] instanceof ObjectHistoneNode ? ((ObjectHistoneNode) args[0]).getElements()
                    : new HashMap<Object, Node>();
    Node methodNode = requestMap.get("method");
    final String method = methodNode != null && methodNode.isString()
            && methodNode.getAsString().getValue().length() != 0
                    ? requestMap.get("method").getAsString().getValue()
                    : "GET";
    final Map<String, String> headers = new HashMap<String, String>();
    if (requestMap.containsKey("headers")) {
        for (Map.Entry<Object, Node> en : requestMap.get("headers").getAsObject().getElements().entrySet()) {
            String value = null;// w w w  .  j av a 2 s.  co m
            if (en.getValue().isUndefined())
                value = "undefined";
            else
                value = en.getValue().getAsString().getValue();
            headers.put(en.getKey().toString(), value);
        }
    }

    final Map<String, String> filteredHeaders = filterRequestHeaders(headers);
    final Node data = requestMap.containsKey("data") ? (Node) requestMap.get("data") : null;

    // Prepare request
    HttpRequestBase request = new HttpGet(newLocation);
    if ("POST".equalsIgnoreCase(method)) {
        request = new HttpPost(newLocation);
    } else if ("PUT".equalsIgnoreCase(method)) {
        request = new HttpPut(newLocation);
    } else if ("DELETE".equalsIgnoreCase(method)) {
        request = new HttpDelete(newLocation);
    } else if ("TRACE".equalsIgnoreCase(method)) {
        request = new HttpTrace(newLocation);
    } else if ("OPTIONS".equalsIgnoreCase(method)) {
        request = new HttpOptions(newLocation);
    } else if ("PATCH".equalsIgnoreCase(method)) {
        request = new HttpPatch(newLocation);
    } else if ("HEAD".equalsIgnoreCase(method)) {
        request = new HttpHead(newLocation);
    } else if (method != null && !"GET".equalsIgnoreCase(method)) {
        return new StreamResource(null, location.toString(), ContentType.TEXT);
    }

    for (Map.Entry<String, String> en : filteredHeaders.entrySet()) {
        request.setHeader(en.getKey(), en.getValue());
    }
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && data != null) {
        String stringData = null;
        String contentType = filteredHeaders.get("content-type") == null ? ""
                : filteredHeaders.get("content-type");
        if (data.isObject()) {
            stringData = ToQueryString.toQueryString(data.getAsObject(), null, "&");
            contentType = "application/x-www-form-urlencoded";
        } else {
            stringData = data.getAsString().getValue();
        }
        if (stringData != null) {
            StringEntity se;
            try {
                se = new StringEntity(stringData);
            } catch (UnsupportedEncodingException e) {
                throw new ResourceLoadException(String.format("Can't encode data '%s'", stringData));
            }
            ((HttpEntityEnclosingRequestBase) request).setEntity(se);
        }
        request.setHeader("Content-Type", contentType);
    }
    if (request.getHeaders("content-Type").length == 0) {
        request.setHeader("Content-Type", "");
    }

    // Execute request
    HttpClient client = new DefaultHttpClient(httpClientConnectionManager);
    ((AbstractHttpClient) client).setRedirectStrategy(new RedirectStrategy());
    InputStream input = null;
    try {
        HttpResponse response = client.execute(request);
        input = response.getEntity() == null ? null : response.getEntity().getContent();
    } catch (IOException e) {
        throw new ResourceLoadException(String.format("Can't load resource '%s'", location.toString()));
    } finally {
    }
    return new StreamResource(input, location.toString(), ContentType.TEXT);
}

From source file:self.philbrown.droidQuery.AjaxTask.java

@Override
protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled())
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {//from   w w w  .j  a  va2 s  .com
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(AjaxTask.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(AjaxTask.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.headers = null;
        return s;

    }

    if (request == null) {
        String type = options.type();
        if (type == null)
            type = "GET";
        if (type.equalsIgnoreCase("DELETE")) {
            request = new HttpDelete(options.url());
        } else if (type.equalsIgnoreCase("GET")) {
            request = new HttpGet(options.url());
        } else if (type.equalsIgnoreCase("HEAD")) {
            request = new HttpHead(options.url());
        } else if (type.equalsIgnoreCase("OPTIONS")) {
            request = new HttpOptions(options.url());
        } else if (type.equalsIgnoreCase("POST")) {
            request = new HttpPost(options.url());
        } else if (type.equalsIgnoreCase("PUT")) {
            request = new HttpPut(options.url());
        } else if (type.equalsIgnoreCase("TRACE")) {
            request = new HttpTrace(options.url());
        } else if (type.equalsIgnoreCase("CUSTOM")) {
            try {
                request = options.customRequest();
            } catch (Exception e) {
                request = null;
            }

            if (request == null) {
                Log.w("droidQuery.ajax",
                        "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                request = new HttpGet();
            }

        } else {
            //default to GET
            request = new HttpGet();
        }
    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", request);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class });
            if (options.processData() == null) {
                setEntity.invoke(request, new StringEntity(options.data().toString()));
            } else {
                Class<?> dataProcessor = Class.forName(options.processData());
                Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class });
                setEntity.invoke(request, constructor.newInstance(options.data()));
            }
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    HttpParams params = new BasicHttpParams();

    if (options.timeout() != 0) {
        HttpConnectionParams.setConnectionTimeout(params, options.timeout());
        HttpConnectionParams.setSoTimeout(params, options.timeout());
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (options.trustAllSSLCertificates()) {
        X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier(hostnameVerifier);
        schemeRegistry.register(new Scheme("https", socketFactory, 443));
        Log.w("Ajax", "Warning: All SSL Certificates have been trusted!");
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);
    HttpClient client = new DefaultHttpClient(mgr, params);

    HttpResponse response = null;
    try {

        if (options.cookies() != null) {
            CookieStore cookies = new BasicCookieStore();
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue()));
            }
            HttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
            response = client.execute(request, httpContext);
        } else {
            response = client.execute(request);
        }

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), response, options.dataType());
            else
                options.dataFilter().invoke(null, response, options.dataType());
        }

        final StatusLine statusLine = response.getStatusLine();

        final Function function = options.statusCode().get(statusLine.getStatusCode());
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusLine.getStatusCode(), options.clone());
                    else
                        function.invoke(null, statusLine.getStatusCode(), options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                parsedResponse = parseText(response);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    InputStream is = response.getEntity().getContent();
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(is, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(is, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    InputStream is = response.getEntity().getContent();

                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(is));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(response);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(response);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(response);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                parsedResponse = parseImage(response);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(response);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.headers = response.getAllHeaders();
            e.error = error;
            return e;
        }

        if (statusLine.getStatusCode() >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = statusLine.getStatusCode();
            e.reason = statusLine.getReasonPhrase();
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.headers = response.getAllHeaders();
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            Header[] lastModifiedHeaders = response.getHeaders("last-modified");
            if (lastModifiedHeaders.length >= 1) {
                try {
                    Header h = lastModifiedHeaders[0];
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h.getValue());
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.request = request;
                            error.options = options;
                            e.status = statusLine.getStatusCode();
                            e.reason = statusLine.getReasonPhrase();
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.headers = response.getAllHeaders();
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = statusLine.getReasonPhrase();
            s.headers = response.getAllHeaders();
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.request = request;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (response != null)
                e.headers = response.getAllHeaders();
            else
                e.headers = new Header[0];
            e.error = error;
            return e;
        }
        return null;
    }
}