下面列出了怎么用org.apache.http.client.methods.HttpHead的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void checkVersionSpecificUpdateCenterTest() throws Exception {
//Test where version specific update center exists
pm.setJenkinsVersion(new VersionNumber("2.176"));
mockStatic(HttpClients.class);
CloseableHttpClient httpclient = mock(CloseableHttpClient.class);
when(HttpClients.createSystem()).thenReturn(httpclient);
HttpHead httphead = mock(HttpHead.class);
whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(httpclient.execute(httphead)).thenReturn(response);
StatusLine statusLine = mock(StatusLine.class);
when(response.getStatusLine()).thenReturn(statusLine);
int statusCode = HttpStatus.SC_OK;
when(statusLine.getStatusCode()).thenReturn(statusCode);
pm.checkAndSetLatestUpdateCenter();
String expected = dirName(cfg.getJenkinsUc()) + pm.getJenkinsVersion() + Settings.DEFAULT_UPDATE_CENTER_FILENAME;
assertEquals(expected, pm.getJenkinsUCLatest());
}
@Test
void testDoHttpHeadContext() throws Exception
{
CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
HttpContext context = mock(HttpContext.class);
when(closeableHttpResponse.getEntity()).thenReturn(null);
StatusLine statusLine = mock(StatusLine.class);
int statusCode = HttpStatus.SC_MOVED_PERMANENTLY;
Header[] headers = { header };
when(closeableHttpResponse.getAllHeaders()).thenReturn(headers);
when(statusLine.getStatusCode()).thenReturn(statusCode);
when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
when(closeableHttpClient.execute(isA(HttpHead.class), eq(context)))
.thenAnswer(getAnswerWithSleep(closeableHttpResponse));
HttpResponse httpResponse = httpClient.doHttpHead(URI_TO_GO, context);
assertEquals(HEAD, httpResponse.getMethod());
assertEquals(URI_TO_GO, httpResponse.getFrom());
assertEquals(statusCode, httpResponse.getStatusCode());
assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L));
assertThat(httpResponse.getResponseHeaders(), is(equalTo(headers)));
}
private boolean checkStatusCode(final String httpMethod, final URL sourceURL, final HttpResponse response) {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
return true;
}
// IVY-1328: some servers return a 204 on a HEAD request
if (HttpHead.METHOD_NAME.equals(httpMethod) && (status == 204)) {
return true;
}
Message.debug("HTTP response status: " + status + " url=" + sourceURL);
if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
Message.warn("Your proxy requires authentication.");
} else if (String.valueOf(status).startsWith("4")) {
Message.verbose("CLIENT ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL);
} else if (String.valueOf(status).startsWith("5")) {
Message.error("SERVER ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL);
}
return false;
}
/**
* 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 sendHttpHead() throws IOException {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
HttpHead head = new HttpHead(DefaultServer.getDefaultServerURL() + "/path");
TestHttpClient client = new TestHttpClient();
try {
generateMessage(1);
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals(message, HttpClientUtils.readResponse(result));
result = client.execute(head);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("", HttpClientUtils.readResponse(result));
generateMessage(1000);
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals(message, HttpClientUtils.readResponse(result));
result = client.execute(head);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Assert.assertEquals("", HttpClientUtils.readResponse(result));
} finally {
client.getConnectionManager().shutdown();
}
}
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());
}
}
/**
* Response to HEAD requests don't have an entity so we shouldn't try to wrap the response in a
* {@link BufferedHttpEntity}.
*/
@Test
public void requestTimeoutEnabled_HeadRequestCompletesWithinTimeout_EntityNotBuffered() throws Exception {
ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0);
ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config);
HttpResponseProxy responseProxy = createHttpHeadResponseProxy();
doReturn(responseProxy).when(rawHttpClient).execute(any(HttpHead.class), any(HttpContext.class));
httpClient = new AmazonHttpClient(config, rawHttpClient, null);
try {
execute(httpClient, createMockHeadRequest());
fail("Exception expected");
} catch (AmazonClientException e) {
NullResponseHandler.assertIsUnmarshallingException(e);
}
assertNull(responseProxy.getEntity());
}
/**
* 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);
}
}
@Override
public HttpUriRequest getRedirect(
final HttpRequest request, final HttpResponse response, final HttpContext context)
throws ProtocolException {
final URI uri = getLocationURI(request, response, context);
final 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 {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_TEMPORARY_REDIRECT
|| status == HttpStatus.SC_MOVED_PERMANENTLY
|| status == HttpStatus.SC_MOVED_TEMPORARILY) {
return RequestBuilder.copy(request).setUri(uri).build();
}
return new HttpGet(uri);
}
}
/**
* <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();
}
}
@Test
@Category({
LDP.class,
HappyPath.class
})
@OperateOnDeployment(DEPLOYMENT)
public void testEnhancedHead(@ArquillianResource final URL url) throws Exception {
LOGGER.info("Started {}",testName.getMethodName());
HELPER.base(url);
HELPER.setLegacy(false);
HELPER.httpRequest(HELPER.newRequest(MyApplication.ROOT_PERSON_RESOURCE_PATH,HttpHead.class));
LOGGER.info("Completed {}",testName.getMethodName());
}
@Test public void createHeadRequest() throws Exception {
TestRequest.Head request = new TestRequest.Head();
assertEquals(request.getMethod(), Method.HEAD);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpHead);
}
@Test(groups = "wso2.esb", description = "test to verify that the HTTP HEAD method works with PTT.")
public void testHttpHeadMethod() throws Exception {
String restURL = (getProxyServiceURLHttp(SERVICE_NAME)) + "/students";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHead httpHead = new HttpHead(restURL);
HttpResponse response = httpclient.execute(httpHead);
// http head method should return a 202 Accepted
assertTrue(response.getStatusLine().getStatusCode() == 202);
// it should not contain a message body
assertTrue(response.getEntity() == null);
}
/**
* Send a HEAD request
* @param cluster the cluster definition
* @param path the path or URI
* @param headers the HTTP headers to include in the request
* @return a Response object with response detail
* @throws IOException
*/
public Response head(Cluster cluster, String path, Header[] headers)
throws IOException {
HttpHead method = new HttpHead(path);
try {
HttpResponse resp = execute(cluster, method, null, path);
return new Response(resp.getStatusLine().getStatusCode(), resp.getAllHeaders(), null);
} finally {
method.releaseConnection();
}
}
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)
);
}
private CloseableHttpResponse doHead(final URL url, final int connectionTimeout, final int readTimeout) throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectionTimeout)
.setAuthenticationEnabled(hasCredentialsConfigured(url))
.setTargetPreferredAuthSchemes(getAuthSchemePreferredOrder())
.setProxyPreferredAuthSchemes(getAuthSchemePreferredOrder())
.build();
final HttpHead httpHead = new HttpHead(normalizeToString(url));
httpHead.setConfig(requestConfig);
return this.httpClient.execute(httpHead);
}
/**
* Send a HEAD request to a given URL to verify accessibility with given credentials.
*
* @param url the URL to verify
* @param username username for authentication (pass null for unauthenticated requests)
* @param password password for authentication (pass null for unauthenticated requests)
* @param ignoreNoProxy set true to ignore the "no_proxy" setting
* @return the response code of the request
* @throws IOException in case of an error
*/
private static HttpResponse sendHeadRequest(String url, String username,
String password, boolean ignoreNoProxy) throws IOException {
HttpClientAdapter httpClient = new HttpClientAdapter();
HttpHead headRequest = new HttpHead(url);
try {
return httpClient.executeRequest(
headRequest, username, password, ignoreNoProxy);
}
finally {
headRequest.releaseConnection();
}
}
@Override
public HttpResponse Head(final String uri) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
final HttpHead head = new HttpHead(uri);
final HttpResponse response = client.execute(head);
return response;
}
/**
* Checks if is valid resource.
*
* @param esUrl the es url
* @return boolean
*/
public static boolean isValidResource(String esUrl) {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpHead httpHead = new HttpHead(esUrl);
HttpResponse response;
try {
response = httpclient.execute(httpHead);
return HttpStatus.SC_OK==response.getStatusLine().getStatusCode();
} catch (ClientProtocolException clientProtocolException) {
logger.error("ClientProtocolException in getHttpHead:"+ clientProtocolException.getMessage());
} catch (IOException ioException) {
logger.error("IOException in getHttpHead:"+ ioException.getMessage());
}
return false;
}
/**
* Checks if is valid resource.
*
* @param esUrl the es url
* @return boolean
*/
public static boolean isValidResource(String esUrl) {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpHead httpHead = new HttpHead(esUrl);
HttpResponse response;
try {
response = httpclient.execute(httpHead);
return HttpStatus.SC_OK == response.getStatusLine().getStatusCode();
} catch (ClientProtocolException clientProtocolException) {
LOGGER.error("ClientProtocolException in getHttpHead:" + clientProtocolException);
} catch (IOException ioException) {
LOGGER.error("IOException in getHttpHead:" + ioException);
}
return false;
}
/**
* Checks if is valid resource test 2.
*
* @throws ClientProtocolException the client protocol exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@SuppressWarnings("unchecked")
@Test
public void isValidResourceTest2() throws ClientProtocolException, IOException {
PowerMockito.when(httpClient.execute((HttpHead) any())).thenThrow(ClientProtocolException.class);
assertFalse(CommonUtils.isValidResource("url"));
}
/**
* Checks if is valid resource test 3.
*
* @throws ClientProtocolException the client protocol exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@SuppressWarnings("unchecked")
@Test
public void isValidResourceTest3() throws ClientProtocolException, IOException {
PowerMockito.when(httpClient.execute((HttpHead) any())).thenThrow(IOException.class);
assertFalse(CommonUtils.isValidResource("url"));
}
/**
* Checks if is valid resource test 4.
*
* @throws ClientProtocolException the client protocol exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@Test
public void isValidResourceTest4() throws ClientProtocolException, IOException {
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_FORBIDDEN, "NOT FINE!"));
PowerMockito.when(httpClient.execute((HttpHead) any())).thenReturn(httpResponse);
assertFalse(CommonUtils.isValidResource("https://sample.com"));
}
@Test
public void createHeadRequest() throws Exception {
TestRequest.Head request = new TestRequest.Head();
assertEquals(request.getMethod(), Method.HEAD);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpHead);
}
/**
* Invoke the endpoint URL using a HTTP HEAD.
*
* @return The response
* @throws HttpException
*/
@PublicAtsApi
public HttpResponse head() throws HttpException {
final URI uri = constructURI();
HttpHead method = new HttpHead(uri);
log.info("We will run a HEAD request from " + uri);
return execute(method);
}
@Test
public void unsupportedMethod() throws Exception {
HttpResponse response = getHttpClient().execute(new HttpHead(getEndpoint()));
assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode());
response = getHttpClient().execute(new HttpOptions(getEndpoint()));
assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode());
}
@Override
public void doHead(URI url, HttpServletRequest request, HttpServletResponse response)
throws IOException {
final HttpHead method = new HttpHead(url);
copyRequestHeaderFields(method, request);
executeRequest(method, request, response);
}
public HttpResponse head(String url) {
try {
return new HttpResponse(client.execute(setAuthorizationHeader(new HttpHead(url))));
} catch (IOException e) {
throw handleException(e);
}
}
HttpRequestBase create(HttpMethod httpMethod) {
if (httpMethod == HttpMethod.GET) {
return new HttpGet();
}
if (httpMethod == HttpMethod.POST) {
return new HttpPost();
}
if (httpMethod == HttpMethod.PUT) {
return new HttpPut();
}
if (httpMethod == HttpMethod.DELETE) {
return new HttpDelete();
}
if (httpMethod == HttpMethod.PATCH) {
return new HttpPatch();
}
if (httpMethod == HttpMethod.HEAD) {
return new HttpHead();
}
throw new UnsupportedOperationException("Method " + httpMethod + " is not supported by apache http-client");
}