List of usage examples for org.apache.http.client.methods HttpOptions HttpOptions
public HttpOptions(final String uri)
From source file:org.greencheek.spring.rest.SSLCachingHttpComponentsClientHttpRequestFactory.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 v a 2 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); // Not supported in 3.0.6 // case PATCH: // return new HttpPatch(uri); default: throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } }
From source file:com.ccc.crest.core.client.CrestClient.java
public Future<EveData> getOptions(CrestRequestData requestData, ClientElement client) { String accessToken = null;/*from w w w. j av a2s. com*/ if (requestData.clientInfo != null) accessToken = ((OAuth2AccessToken) requestData.clientInfo.getAccessToken()).getAccessToken(); HttpOptions get = new HttpOptions(requestData.url); if (accessToken != null) { get.addHeader("Authorization", "Bearer " + accessToken); if (requestData.scope != null) get.addHeader("Scope", requestData.scope); } if (requestData.version != null) get.addHeader("Accept", requestData.version); return executor.submit(new CrestGetTask(client, get, requestData)); }
From source file:ch.entwine.weblounge.test.harness.content.HTMLActionTest.java
/** * Tests whether the action returns its url correctly. * /*from w w w. java 2 s .co m*/ * @param serverUrl * the server url */ private void testActionURL(String serverUrl) { // Prepare the request logger.info("Testing action url"); HttpOptions request = new HttpOptions(UrlUtils.concat(serverUrl, defaultActionPath)); // Send the request and make sure it ends up on the expected page logger.info("Sending request to {}", request.getURI()); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = TestUtils.request(httpClient, request, null); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); // Make sure there is a Location header in the response Header locationHeader = response.getFirstHeader("Location"); assertNotNull("Action did not return 'Location' header", locationHeader); String location = locationHeader.getValue(); // Check that the action's url starts with the correct environment assertEquals("Action reports invalid url", defaultActionPath + "/", location); } catch (Throwable e) { fail("Request to " + request.getURI() + " failed" + e.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java
public WireMockResponse options(String url, TestHttpHeader... headers) { HttpOptions httpOptions = new HttpOptions(mockServiceUrlFor(url)); return executeMethodAndConvertExceptions(httpOptions, headers); }
From source file:org.apache.cxf.systest.jaxrs.cors.CrossOriginSimpleTest.java
@Test public void preflightPostClassAnnotationFail2() throws ClientProtocolException, IOException { HttpClient httpclient = HttpClientBuilder.create().build(); HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost"); httpoptions.addHeader("Origin", "http://area51.mil:31415"); httpoptions.addHeader("Content-Type", "application/json"); httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST"); httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-3"); HttpResponse response = httpclient.execute(httpoptions); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN).length); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS).length); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS).length); if (httpclient instanceof Closeable) { ((Closeable) httpclient).close(); }/*from ww w . ja v a2 s .c o m*/ }
From source file:self.philbrown.javaQuery.AjaxTask.java
@Override protected TaskResponse doInBackground(Void... arg0) { //handle cached responses CachedResponse cachedResponse = URLresponses .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType())); //handle ajax caching option if (cachedResponse != null) { if (options.cache()) { if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) { //return cached response Success s = new Success(); s.obj = cachedResponse.response; s.reason = "cached response"; s.headers = null;/* w w w.j a v a2s. com*/ 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("javaQuery.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()); } HttpClient client = new DefaultHttpClient(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(new $(options.context()), response, options.dataType()); else options.dataFilter().invoke(null, response, options.dataType()); } StatusLine statusLine = response.getStatusLine(); Function function = options.statusCode().get(statusLine); if (function != null) { if (options.context() != null) function.invoke(new $(options.context())); else function.invoke(null); } if (statusLine.getStatusCode() >= 300) { //an error occurred Error e = new Error(); 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; e.headers = response.getAllHeaders(); e.error = error; return e; } else { //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; Object parsedResponse = null; boolean success = true; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { parsedResponse = parseText(response); } else if (dataType.equalsIgnoreCase("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")) { parsedResponse = parseJSON(response); } else if (dataType.equalsIgnoreCase("script")) { parsedResponse = parseScript(response); } else if (dataType.equalsIgnoreCase("image")) { parsedResponse = parseImage(response); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); success = false; Error e = new Error(); 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; e.headers = response.getAllHeaders(); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); success = false; Error e = new Error(); 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; e.headers = response.getAllHeaders(); e.error = error; return e; } if (success) { //Handle cases where successful requests still return errors (these include //configurations in AjaxOptions and HTTP Headers String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()); CachedResponse cache = URLresponses.get(key); Date now = new Date(); //handle ajax caching option if (cache != null) { if (options.cache()) { if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) { parsedResponse = cache; } else { cache.response = parsedResponse; cache.timestamp = now; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } //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"); Date lastModified = format.parse(h.getValue()); if (options.ifModified() && lastModified != null) { if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(); 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; e.headers = response.getAllHeaders(); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke(new $(options.context())); else func.invoke(null); } return e; } else { cache.lastModified = lastModified; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header"); } } //Now handle a successful request Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } //success Success s = new Success(); s.obj = 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(); AjaxError error = new AjaxError(); error.request = request; error.options = options; 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; } }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
static HttpUriRequest getRequest(HttpMethod method, String url) { if (method == HttpMethod.GET) { return new HttpGet(url); } else if (method == HttpMethod.POST) { return new HttpPost(url); } else if (method == HttpMethod.PUT) { return new HttpPut(url); } else if (method == HttpMethod.DELETE) { return new HttpDelete(url); } else if (method == HttpMethod.HEAD) { return new HttpHead(url); } else if (method == HttpMethod.OPTIONS) { return new HttpOptions(url); } else if (method == HttpMethod.TRACE) { return new HttpTrace(url); } else {/* w w w .java 2s.co m*/ return null; } }
From source file:sabina.integration.TestScenario.java
private HttpUriRequest getHttpRequest(String method, String path, String body, boolean secure, String acceptType) {//from w w w.j a va2 s . c om if (body == null) body = ""; try { String protocol = secure ? "https" : "http"; String uri = protocol + "://localhost:" + port + path; if (method.equals("GET")) { HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Accept", acceptType); return httpGet; } if (method.equals("POST")) { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("Accept", acceptType); httpPost.setEntity(new StringEntity(body)); return httpPost; } if (method.equals("PATCH")) { HttpPatch httpPatch = new HttpPatch(uri); httpPatch.setHeader("Accept", acceptType); httpPatch.setEntity(new StringEntity(body)); return httpPatch; } if (method.equals("DELETE")) { HttpDelete httpDelete = new HttpDelete(uri); httpDelete.setHeader("Accept", acceptType); return httpDelete; } if (method.equals("PUT")) { HttpPut httpPut = new HttpPut(uri); httpPut.setHeader("Accept", acceptType); httpPut.setEntity(new StringEntity(body)); return httpPut; } if (method.equals("HEAD")) return new HttpHead(uri); if (method.equals("TRACE")) return new HttpTrace(uri); if (method.equals("OPTIONS")) return new HttpOptions(uri); throw new IllegalArgumentException("Unknown method " + method); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:org.olat.core.commons.services.webdav.WebDAVConnection.java
public HttpOptions createOptions(URI uri) throws IOException, URISyntaxException { HttpOptions options = new HttpOptions(uri); return options; }
From source file:de.taimos.httputils.HTTPRequest.java
/** * @return the {@link HttpResponse}/*from w ww.j av a2s .co m*/ */ public HttpResponse options() { return this.execute(new HttpOptions(this.buildURI())); }