下面列出了怎么用org.apache.http.client.methods.HttpOptions的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param httpMethod the HTTP method
* @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 HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case PATCH:
return new HttpPatch(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case TRACE:
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param httpMethod the HTTP method
* @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 HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case PATCH:
return new HttpPatch(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case TRACE:
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param httpMethod the HTTP method
* @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 HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case PATCH:
return new HttpPatch(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case TRACE:
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, String uri) {
switch (request.httpRequest().method()) {
case HEAD:
return new HttpHead(uri);
case GET:
return new HttpGet(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case PATCH:
return wrapEntity(request, new HttpPatch(uri));
case POST:
return wrapEntity(request, new HttpPost(uri));
case PUT:
return wrapEntity(request, new HttpPut(uri));
default:
throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
}
}
private HttpRequestBase createApacheRequest(Request<?> request, String uri, String encodedParams) throws FakeIOException {
switch (request.getHttpMethod()) {
case HEAD:
return new HttpHead(uri);
case GET:
return new HttpGet(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case PATCH:
return wrapEntity(request, new HttpPatch(uri), encodedParams);
case POST:
return wrapEntity(request, new HttpPost(uri), encodedParams);
case PUT:
return wrapEntity(request, new HttpPut(uri), encodedParams);
default:
throw new SdkClientException("Unknown HTTP method name: " + request.getHttpMethod());
}
}
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param httpMethod the HTTP method
* @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 HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case PATCH:
return new HttpPatch(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case TRACE:
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
@Test
public void requireThatServerRespondsToAllMethods() throws Exception {
final TestDriver driver = TestDrivers.newInstance(newEchoHandler());
final URI uri = driver.client().newUri("/status.html");
driver.client().execute(new HttpGet(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpPost(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpHead(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpPut(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpDelete(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpOptions(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpTrace(uri))
.expectStatusCode(is(OK));
driver.client().execute(new HttpPatch(uri))
.expectStatusCode(is(OK));
assertThat(driver.close(), is(true));
}
/**
* Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
* @param method the HTTP method
* @param uri the URI
* @return the Commons HttpMethodBase object
*/
private static HttpUriRequest createHttpUriRequest(String method, URI uri) {
switch (method) {
case "GET":
return new HttpGet(uri);
case "HEAD":
return new HttpHead(uri);
case "POST":
return new HttpPost(uri);
case "PUT":
return new HttpPut(uri);
case "PATCH":
return new HttpPatch(uri);
case "DELETE":
return new HttpDelete(uri);
case "OPTIONS":
return new HttpOptions(uri);
case "TRACE":
return new HttpTrace(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + method);
}
}
protected HttpUriRequest buildHttpRequest(Method method, URI uri) {
switch (method) {
case OPTIONS:
return new HttpOptions(uri);
case GET:
return new HttpGet(uri);
case HEAD:
return new HttpHead(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case DELETE:
return new HttpDelete(uri);
case TRACE:
return new HttpTrace(uri);
case PATCH:
return new HttpPatch(uri);
default:
throw new IllegalArgumentException("Method " + method + " is not implemented!");
}
}
static boolean isResponseContentValid(String url) {
if ("true".equals(System.getProperty("bash.skipUrls", "false"))) {
return true;
}
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
CloseableHttpResponse response = httpClient.execute(new HttpOptions(url));
Assert.assertTrue("Expected response content for " + url, 404 != response.getStatusLine().getStatusCode());
String content = EntityUtils.toString(response.getEntity());
return !content.contains("No matches for");
} catch (Exception e) {
return false;
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
private HttpUriRequest resolveMethod( String _method, boolean _multipart ) throws cfmRunTimeException {
String method = _method.toUpperCase();
if ( method.equals( "GET" ) ) {
return new HttpGet();
} else if ( method.equals( "POST" ) ) {
return new HttpPost();
} else if ( method.equals( "HEAD" ) ) {
return new HttpHead();
} else if ( method.equals( "TRACE" ) ) {
return new HttpTrace();
} else if ( method.equals( "DELETE" ) ) {
return new HttpDelete();
} else if ( method.equals( "OPTIONS" ) ) {
return new HttpOptions();
} else if ( method.equals( "PUT" ) ) {
return new HttpPut();
} else if ( method.equals( "PATCH" ) ) {
return new HttpPatch();
}
throw newRunTimeException( "Unsupported METHOD value [" + method + "]. Valid METHOD values are GET, POST, HEAD, TRACE, DELETE, OPTIONS, PATCH and PUT." );
}
@Test
public void preflightPostClassAnnotationFail() throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin", "http://in.org");
// nonsimple header
httpoptions.addHeader("Content-Type", "application/json");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-1");
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();
}
}
@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();
}
}
@Test
public void preflightPostClassAnnotationPass() 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-1");
HttpResponse response = httpclient.execute(httpoptions);
assertEquals(200, response.getStatusLine().getStatusCode());
Header[] origin = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
assertEquals(1, origin.length);
assertEquals("http://area51.mil:31415", origin[0].getValue());
Header[] method = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
assertEquals(1, method.length);
assertEquals("POST", method[0].getValue());
Header[] requestHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
assertEquals(1, requestHeaders.length);
assertEquals("X-custom-1", requestHeaders[0].getValue());
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
@Test
public void preflightPostClassAnnotationPass2() 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-1, X-custom-2");
HttpResponse response = httpclient.execute(httpoptions);
assertEquals(200, response.getStatusLine().getStatusCode());
Header[] origin = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
assertEquals(1, origin.length);
assertEquals("http://area51.mil:31415", origin[0].getValue());
Header[] method = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
assertEquals(1, method.length);
assertEquals("POST", method[0].getValue());
Header[] requestHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
assertEquals(1, requestHeaders.length);
assertTrue(requestHeaders[0].getValue().contains("X-custom-1"));
assertTrue(requestHeaders[0].getValue().contains("X-custom-2"));
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
@Test
public void testAnnotatedLocalPreflightNoGo() throws Exception {
configureAllowOrigins(true, null);
String r = configClient.replacePath("/setAllowCredentials/false")
.accept("text/plain").post(null, String.class);
assertEquals("ok", r);
HttpClient httpclient = HttpClientBuilder.create().build();
HttpOptions http = new HttpOptions("http://localhost:" + PORT + "/antest/delete");
// this is the origin we expect to get.
http.addHeader("Origin", "http://area51.mil:4444");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "DELETE");
HttpResponse response = httpclient.execute(http);
assertEquals(200, response.getStatusLine().getStatusCode());
assertOriginResponse(false, new String[]{"http://area51.mil:4444"}, false, response);
// we could check that the others are also missing.
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
/**
* <p>Retrieves the proper extension of {@link HttpRequestBase} for the given {@link InvocationContext}.
* This implementation is solely dependent upon the {@link RequestMethod} property in the annotated
* metdata of the endpoint method definition.</p>
*
* @param context
* the {@link InvocationContext} for which a {@link HttpRequestBase} is to be generated
* <br><br>
* @return the {@link HttpRequestBase} translated from the {@link InvocationContext}'s {@link RequestMethod}
* <br><br>
* @throws NullPointerException
* if the supplied {@link InvocationContext} was {@code null}
* <br><br>
* @since 1.3.0
*/
static HttpRequestBase translateRequestMethod(InvocationContext context) {
RequestMethod requestMethod = Metadata.findMethod(assertNotNull(context).getRequest());
switch (requestMethod) {
case POST: return new HttpPost();
case PUT: return new HttpPut();
case PATCH: return new HttpPatch();
case DELETE: return new HttpDelete();
case HEAD: return new HttpHead();
case TRACE: return new HttpTrace();
case OPTIONS: return new HttpOptions();
case GET: default: return new HttpGet();
}
}
static Stream<Arguments> successfulEmptyRequestCreation()
{
return Stream.of(
Arguments.of(HttpMethod.GET, HttpGet.class),
Arguments.of(HttpMethod.HEAD, HttpHead.class),
Arguments.of(HttpMethod.DELETE, HttpDelete.class),
Arguments.of(HttpMethod.OPTIONS, HttpOptions.class),
Arguments.of(HttpMethod.TRACE, HttpTrace.class),
Arguments.of(HttpMethod.POST, HttpPost.class),
Arguments.of(HttpMethod.PUT, HttpPutWithoutBody.class),
Arguments.of(HttpMethod.DEBUG, HttpDebug.class)
);
}
@Test
public void createOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
@Test public void createOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
@Test public void createOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
public void testCreateOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
@Test
public void preFlightAllowedMethod() throws Exception {
URI uri = new URI("http", null /*preflight requires no auth*/, "localhost", port, entityEndpoint(), null, null);
HttpUriRequest request = new HttpOptions(uri);
request.setHeader("Origin", ORIGIN);
request.setHeader("Access-Control-Request-Method", "PUT");
response = client.execute(request);
assertEquals("status", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("Allow-Origin", ORIGIN, headerValue(response, HEADER_ALLOW_ORIGIN));
}
@Test
public void preFlightDisallowedMethod() throws Exception {
URI uri = new URI("http", null /*preflight requires no auth*/, "localhost", port, entityEndpoint(), null, null);
HttpUriRequest request = new HttpOptions(uri);
request.setHeader("Origin", ORIGIN);
request.setHeader("Access-Control-Request-Method", "DELETE");
response = client.execute(request);
assertEquals("status", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
assertEquals("Allow-Origin", null, headerValue(response, HEADER_ALLOW_ORIGIN));
}
@Test public void createOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
@Test public void createOptionsRequest() throws Exception {
TestRequest.Options request = new TestRequest.Options();
assertEquals(request.getMethod(), Method.OPTIONS);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpOptions);
}
@Override
public HttpUriRequest getRedirect(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
URI uri = null;
try {
uri = getLocationURI(request, response, context);
} catch (URISyntaxException ex) {
Logger.getLogger(CustomRedirectStrategy.class.getName()).log(Level.SEVERE, null, ex);
}
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 {
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);
}
}
@Override
public HttpResponse Options(final String uri) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
final HttpOptions options = new HttpOptions(uri);
final HttpResponse response = client.execute(options);
return response;
}
/**
* Creates the appropriate subclass of HttpUriRequest for passed in request.
*/
static HttpRequestBase createHttpRequest(
Request<?> request, Map<String, String> additionalHeaders) {
switch (request.getMethod()) {
case Request.Method.GET:
return new HttpGet(request.getUrlString());
case Request.Method.DELETE:
return new HttpDelete(request.getUrlString());
case Request.Method.POST: {
HttpPost postRequest = new HttpPost(request.getUrlString());
postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(postRequest, request);
return postRequest;
}
case Request.Method.PUT: {
HttpPut putRequest = new HttpPut(request.getUrlString());
putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest, request);
return putRequest;
}
case Request.Method.HEAD:
return new HttpHead(request.getUrlString());
case Request.Method.OPTIONS:
return new HttpOptions(request.getUrlString());
case Request.Method.TRACE:
return new HttpTrace(request.getUrlString());
case Request.Method.PATCH: {
HttpPatch patchRequest = new HttpPatch(request.getUrlString());
patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
setEntityIfNonEmptyBody(patchRequest, request);
return patchRequest;
}
default:
throw new IllegalStateException("Unknown request method.");
}
}
@Test
public void testOptions() throws Exception {
final HttpURLConnection connection = getConnection();
connection.setRequestMethod(HttpOptions.METHOD_NAME);
connection.connect();
assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, connection.getResponseCode());
}