下面列出了怎么用org.apache.http.client.methods.HttpRequestBase的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void requestTimeoutDisabled_RequestCompletesWithinTimeout_EntityNotBuffered() throws Exception {
ClientConfiguration config = new ClientConfiguration().withRequestTimeout(0);
ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config);
HttpResponseProxy responseProxy = createHttpResponseProxySpy();
doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class));
httpClient = new AmazonHttpClient(config, rawHttpClient, null);
try {
execute(httpClient, createMockGetRequest());
fail("Exception expected");
} catch (AmazonClientException e) {
}
assertResponseWasNotBuffered(responseProxy);
}
/**
* 发送 http 请求
* @param httpRequestBase request
* @param client http client
* @return response
*/
private String sendRequest(HttpRequestBase httpRequestBase,HttpClient client){
String result = null;
try {
HttpResponse response = client.execute(httpRequestBase);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity, "UTF-8");
EntityUtils.consume(httpEntity);
} else {
log.error("请求异常:{},{}", httpRequestBase.getURI(), response.getStatusLine());
}
return result;
} catch (IOException e) {
log.error("请求异常:{},{}", httpRequestBase.getURI(), e.getMessage());
}
return "";
}
/**
* Call the transformation service with the export parameters in json the request body.
*
* @param parameters the aggregate parameters.
* @return the http request to execute.
*/
private HttpRequestBase onExecute(AggregationParameters parameters) {
// must work on either a dataset or a preparation, if both parameters are set, an error is thrown
if (StringUtils.isNotBlank(parameters.getDatasetId())
&& StringUtils.isNotBlank(parameters.getPreparationId())) {
LOG.error("Cannot aggregate on both dataset id & preparation id : {}", parameters);
throw new TDPException(CommonErrorCodes.BAD_AGGREGATION_PARAMETERS);
}
String uri = transformationServiceUrl + "/aggregate"; //$NON-NLS-1$
HttpPost aggregateCall = new HttpPost(uri);
try {
String paramsAsJson = objectMapper.writer().writeValueAsString(parameters);
aggregateCall.setEntity(new StringEntity(paramsAsJson, ContentType.APPLICATION_JSON));
} catch (JsonProcessingException e) {
throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, e);
}
return aggregateCall;
}
/**
* {@inheritDoc}
*/
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
Betamax wizard = w.get();
if(wizard == null) {
return null;
}
String requestURL = "https://";
String provider = wizard.providerListPref.getValue();
if (provider != null) {
String[] set = providers.get(provider);
requestURL += set[0].replace("sip.", "www.");
requestURL += "/myaccount/getbalance.php";
requestURL += "?username=" + acc.username;
requestURL += "&password=" + acc.data;
return new HttpGet(requestURL);
}
return null;
}
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());
}
}
@Override
public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
HttpHost host = (HttpHost) invocation.getArguments()[0];
HttpRequestBase request = (HttpRequestBase) invocation.getArguments()[1];
HttpContext context = (HttpContext) invocation.getArguments()[2];
InputStream response = null;
if(request instanceof HttpGet)
response = doGet(host, (HttpGet) request, context);
else if(request instanceof HttpPost)
response = doPost(host, (HttpPost) request, context);
else if(request instanceof HttpPut)
response = doPut(host, (HttpPut) request, context);
else
throw new Exception("mock method not implemented");
return buildResponse(response);
}
private String sendAndGetResponse(HttpRequestBase request) throws IOException {
String data = StringUtils.EMPTY;
try {
HttpResponse response = client.execute(request, null).get(30, TimeUnit.SECONDS);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
try (InputStream responseContent = response.getEntity().getContent()) {
data = IOUtils.toString(responseContent, "UTF-8");
}
} else {
LOG.error("ZeppelinHub {} {} returned with status {} ", request.getMethod(),
request.getURI(), code);
throw new IOException("Cannot perform " + request.getMethod() + " request to ZeppelinHub");
}
} catch (InterruptedException | ExecutionException | TimeoutException
| NullPointerException e) {
throw new IOException(e);
}
return data;
}
private HttpRequestBase onExecute(String preparationId, String stepId, AppendStep updatedStep) {
try {
final String url = preparationServiceUrl + "/preparations/" + preparationId + "/actions/" + stepId;
final Optional<StepDiff> firstStepDiff = toStream(StepDiff.class, objectMapper, input).findFirst();
if (firstStepDiff.isPresent()) { // Only interested in first one
final StepDiff diff = firstStepDiff.get();
updatedStep.setDiff(diff);
}
final String stepAsString = objectMapper.writeValueAsString(updatedStep);
final HttpPut actionAppend = new HttpPut(url);
final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes());
actionAppend.setHeader(new BasicHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE));
actionAppend.setEntity(new InputStreamEntity(stepInputStream));
return actionAppend;
} catch (IOException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
/**
* GET object
*
* @param path path to the object
* @param account Joss Account wrapper object
* @param bytesFrom from from
* @param bytesTo bytes to
* @param scm Swift Connection manager
* @return SwiftInputStreamWrapper that includes input stream and length
* @throws IOException if network errors
*/
public static SwiftInputStreamWrapper getObject(
final Path path,
final JossAccount account,
final long bytesFrom,
final long bytesTo,
final SwiftConnectionManager scm) throws IOException {
Tuple<Integer, Tuple<HttpRequestBase, HttpResponse>> resp = httpGET(
path.toString(),
bytesFrom,
bytesTo,
account,
scm);
if (resp.x.intValue() >= 400) {
LOG.warn("Re-authentication attempt for GET {}", path.toString());
account.authenticate();
resp = httpGET(path.toString(), bytesFrom, bytesTo, account, scm);
}
final SwiftInputStreamWrapper httpStream = new SwiftInputStreamWrapper(
resp.y.y.getEntity(), resp.y.x
);
return httpStream;
}
@Test
void shouldPassAllParametersToPostForRegistrationOfNonElasticAgent() throws IOException {
String url = "http://cruise.com/go";
GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
when(response.getEntity()).thenReturn(new StringEntity(""));
when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
Properties properties = new Properties();
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "", "")));
}
public static void validateSchemaList(SCIMObject scimObject,
SCIMResourceTypeSchema resourceSchema,
HttpRequestBase method,
String responseString,
String headerString,
String responseStatus,
ArrayList<String> subTests)
throws GeneralComplianceException, ComplianceException {
//get resource schema list
List<String> resourceSchemaList = resourceSchema.getSchemasList();
//get the scim object schema list
List<String> objectSchemaList = scimObject.getSchemaList();
for (String schema : resourceSchemaList) {
//check for schema.
if (!objectSchemaList.contains(schema)) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Schema List Test",
"Not all schemas are set", ComplianceUtils.getWire(method,
responseString, headerString, responseStatus, subTests)));
}
}
}
/**
* {@inheritDoc }
*/
@Override
public ODataInvokeResponse<T> execute() {
final InputStream input = getPayload();
if (!this.parameters.isEmpty()) {
if (this.method == HttpMethod.GET) {
((HttpRequestBase) this.request).setURI(
URIUtils.buildFunctionInvokeURI(this.uri, parameters));
} else if (this.method == HttpMethod.POST) {
((HttpPost) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input));
setContentType(getActualFormat(getPOSTParameterFormat()));
}
}
try {
return new ODataInvokeResponseImpl(odataClient, httpClient, doExecute());
} finally {
IOUtils.closeQuietly(input);
}
}
@Override
protected HttpResponse doExecute() throws Exception {
final HttpMethod method = getMethod();
final HttpRequestBase httpRequest = FACTORY.create(method);
httpRequest.setURI(createRequestURI());
handleBody(httpRequest);
handleHeaders(httpRequest);
handleCookies(httpRequest);
final long start = nanoTime();
final org.apache.http.HttpResponse httpResponse = client.execute(httpRequest);
final long duration = nanoTime() - start;
return ApacheHttpResponseFactory.of(httpResponse, duration);
}
private HttpRequestBase onExecute(final String parentId, final Sort sort, final Order order) {
try {
String uri = preparationServiceUrl + "/folders";
final URIBuilder uriBuilder = new URIBuilder(uri);
if (parentId != null) {
uriBuilder.addParameter("parentId", parentId);
}
if (sort != null) {
uriBuilder.addParameter("sort", sort.camelName());
}
if (order != null) {
uriBuilder.addParameter("order", order.camelName());
}
return new HttpGet(uriBuilder.build());
} catch (URISyntaxException e) {
throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
}
}
private static String httpRequestBaseParse(Object obj) throws IOException {
HttpRequestBase request = (HttpRequestBase)obj;
StringBuilder sb = new StringBuilder();
Header[] headers = request.getAllHeaders();
sb.append(request.getRequestLine().toString()+"\n");
for (Header header : headers) {
sb.append(header.getName() + ": " + header.getValue()+"\n");
}
sb.append("\n");
if(request instanceof HttpPost)
sb.append( EntityUtils.toString(((HttpPost) request).getEntity()));
return sb.toString();
}
public String getHttp(String url, List<NameValuePair> headers) throws IOException
{
HttpRequestBase request = new HttpGet(url);
if (headers != null)
{
for (NameValuePair header : headers)
{
request.addHeader(header.getName(), header.getValue());
}
}
HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
return EntityUtils.toString(entity);
}
return null;
}
public HttpRequestBase getRequest() {
if (target == null) {
throw new IllegalStateException("ServiceCommand has no target url");
}
if (this.httpMethod.equalsIgnoreCase(TYPE_GET)) {
return new HttpGet(target);
} else if (this.httpMethod.equalsIgnoreCase(TYPE_POST)) {
return new HttpPost(target);
} else if (this.httpMethod.equalsIgnoreCase(TYPE_DEL)) {
return new HttpDelete(target);
} else if (this.httpMethod.equalsIgnoreCase(TYPE_PUT)) {
return new HttpPut(target);
} else {
return null;
}
}
protected <T> T execute(HttpRequestBase request, IOFunction<T> resultConverter, Supplier<String> errorSupplier) throws IOException {
try {
activeExecutions.incrementAndGet();
return client.execute(
request,
r -> {
if (r.getStatusLine().getStatusCode() != 200) {
throw new ClientProtocolException("Unable to " + errorSupplier.get() + ": " + r.getStatusLine() + " "
+ EntityUtils.toString(r.getEntity()));
} else {
return resultConverter.apply(r.getEntity());
}
});
} finally {
activeExecutions.decrementAndGet();
}
}
private Object handleResponse(BasicGalaxyRequest basicgalaxyrequest, Class class1, HttpRequestBase httprequestbase, HttpResponse httpresponse, ExecutionContext executioncontext)
{
GalaxyMarshaller galaxymarshaller = executioncontext.getMarshaller();
InputStream inputstream = httpresponse.getEntity().getContent();
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte abyte0[] = new byte[1024];
String s;
do
{
int i = inputstream.read(abyte0);
if (i <= 0)
{
s = new String(bytearrayoutputstream.toString("UTF-8"));
if (class1.isAssignableFrom(java/lang/String))
{
return s;
}
break;
}
bytearrayoutputstream.write(abyte0, 0, i);
} while (true);
if (StringUtils.isBlank(s))
{
return galaxymarshaller.unmarshall(class1, galaxymarshaller.marshall(ReturnCode.RESPONSE_IS_BLANK.getResult()));
} else
{
return galaxymarshaller.unmarshall(class1, s);
}
}
@Test
public void ceateSetsHostHeaderByDefault() {
SdkHttpRequest sdkRequest = SdkHttpRequest.builder()
.uri(URI.create("http://localhost:12345/"))
.method(SdkHttpMethod.HEAD)
.build();
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(sdkRequest)
.build();
HttpRequestBase result = instance.create(request, requestConfig);
Header[] hostHeaders = result.getHeaders(HttpHeaders.HOST);
assertNotNull(hostHeaders);
assertEquals(1, hostHeaders.length);
assertEquals("localhost:12345", hostHeaders[0].getValue());
}
public SwiftInputStreamWrapper(HttpEntity entity, HttpRequestBase httpRequestT)
throws IOException {
super(entity.getContent());
/*
* Http entity that contains the input stream
*/
httpRequest = httpRequestT;
}
@Test
void buildPostWithContent() throws HttpRequestBuildException, IOException
{
HttpRequestBase request = builder.withHttpMethod(HttpMethod.POST).withEndpoint(ENDPOINT).withContent(CONTENT)
.build();
assertRequestWithContent(request, HttpMethod.POST.name(), ENDPOINT, CONTENT);
}
private HttpRequestBase onExecute(String id) {
try {
URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/steps/" + id);
return new HttpGet(uriBuilder.build());
} catch (URISyntaxException e) {
throw new TDPException(UNEXPECTED_EXCEPTION, e);
}
}
/**
* This method is used to set the Authorization header for the request sent to consent management service
*
* @param httpMethod The method which requires to add the Authorization header
* @param tenantDomain The tenant domain
* @throws APIManagementException APIManagement Exception
*/
private static void setAuthorizationHeader(HttpRequestBase httpMethod, String tenantDomain)
throws APIManagementException {
UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
String adminUsername = signupConfig.getAdminUserName();
String adminPassword = signupConfig.getAdminPassword();
String toEncode = adminUsername + ":" + adminPassword;
byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
String authHeader = new String(encoding, Charset.defaultCharset());
httpMethod.addHeader(HTTPConstants.HEADER_AUTHORIZATION,
APIConstants.AUTHORIZATION_HEADER_BASIC + " " + authHeader);
}
@ParameterizedTest
@MethodSource("successfulEmptyRequestCreation")
void testSuccessfulEmptyRequestCreation(HttpMethod httpMethod, Class<? extends HttpRequestBase> requestClass)
{
HttpRequestBase request = httpMethod.createRequest(URI_EXAMPLE);
assertThat(request, instanceOf(requestClass));
assertEquals(URI_EXAMPLE, request.getURI());
}
/**
* Gets a JSON response to an HTTP call
*
* @param httpClient HTTP client to use for call
* @param auth Authentication header contents, or null
* @param inputString REST call to make
* @return response from the inputString
* @throws IOException
*/
static JsonObject getGsonResponse(CloseableHttpClient httpClient,
HttpRequestBase request) throws IOException {
request.addHeader("accept",
ContentType.APPLICATION_JSON.getMimeType());
try (CloseableHttpResponse response = httpClient.execute(request)) {
return gsonFromResponse(response);
}
}
@Override
public <T> T execute(final HttpRequestBase request, final ResponseHandler<T> responseHandler) throws IOException {
if(StringUtils.isNotBlank(request.getURI().getRawQuery())) {
request.setURI(URI.create(String.format("%s%s?%s", uri, request.getURI().getRawPath(), request.getURI().getRawQuery())));
}
else {
request.setURI(URI.create(String.format("%s%s", uri, request.getURI().getRawPath())));
}
return super.execute(request, responseHandler);
}
private static void addDefaultHeaders(HttpRequestBase request) {
request.addHeader("Accept", "application/json");
request.addHeader("X-Forwarded-User", "user");
request.addHeader("SYNDESIS-XSRF-TOKEN", "awesome");
request.addHeader("X-Forwarded-Access-Token", "supersecret");
request.addHeader("Content-Type", "application/json");
}
public static String requestToString(HttpRequestBase httpReq) throws ParseException, IOException {
final StringBuilder builder = new StringBuilder("\n")
.append(httpReq.getMethod())
.append(" ")
.append(httpReq.getURI())
.append(headersToString(httpReq.getAllHeaders()));
if (httpReq instanceof HttpEntityEnclosingRequestBase) {
builder.append("request body:").append(entityToPrettyString(((HttpEntityEnclosingRequestBase) httpReq)
.getEntity()));
}
return builder.toString();
}
/**
* @param preparationId the preparation id.
* @param columnId the column id.
* @param stepId the step id.
* @return the http request to execute.
*/
private Supplier<HttpRequestBase> onExecute(String preparationId, String columnId, String stepId) {
return () -> {
String uri =
transformationServiceUrl + "/preparations/" + preparationId + "/columns/" + columnId + "/types";
if (StringUtils.isNotBlank(stepId)) {
uri += "?stepId=" + stepId;
}
return new HttpGet(uri);
};
}