org.apache.http.client.methods.HttpRequestBase Java Examples
The following examples show how to use
org.apache.http.client.methods.HttpRequestBase.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheHttpRequestFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 7 votes |
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()); } }
Example #2
Source File: RemoteHttpService.java From datawave with Apache License 2.0 | 6 votes |
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(); } }
Example #3
Source File: Aggregate.java From data-prep with Apache License 2.0 | 6 votes |
/** * 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; }
Example #4
Source File: MockedClientTests.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: Betamax.java From CSipSimple with GNU General Public License v3.0 | 6 votes |
/** * {@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; }
Example #6
Source File: HttpResponseMock.java From iaf with Apache License 2.0 | 6 votes |
@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); }
Example #7
Source File: HttpProxyClient.java From zeppelin with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: PreparationUpdateAction.java From data-prep with Apache License 2.0 | 6 votes |
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); } }
Example #9
Source File: SwiftAPIDirect.java From stocator with Apache License 2.0 | 6 votes |
/** * 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; }
Example #10
Source File: ResponseValidateTests.java From scim2-compliance-test-suite with Apache License 2.0 | 6 votes |
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))); } } }
Example #11
Source File: AbstractODataInvokeRequest.java From olingo-odata4 with Apache License 2.0 | 6 votes |
/** * {@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); } }
Example #12
Source File: ApacheHttpRequest.java From junit-servers with MIT License | 6 votes |
@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); }
Example #13
Source File: FolderChildrenList.java From data-prep with Apache License 2.0 | 6 votes |
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); } }
Example #14
Source File: ParseGenerator.java From droidmon with GNU General Public License v3.0 | 6 votes |
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(); }
Example #15
Source File: HTTPClient.java From poloniex-api-java with MIT License | 6 votes |
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; }
Example #16
Source File: RemoteRegistrationRequesterTest.java From gocd with Apache License 2.0 | 6 votes |
@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(), "", ""))); }
Example #17
Source File: ServiceCommand.java From Connect-SDK-Android-Core with Apache License 2.0 | 6 votes |
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; } }
Example #18
Source File: HttpUtil.java From ticket with GNU General Public License v3.0 | 6 votes |
/** * 发送 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 ""; }
Example #19
Source File: ScipioHttpSolrClient.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * Sets basic auth header to either the one in the SolrRequest or the one stored in this client. * <p> * DEV NOTE: Derived from <code>HttpSolrClient#setBasicAuthHeader</code>, which is private in superclass. */ @SuppressWarnings("rawtypes") protected void setBasicAuthHeaderScipio(SolrRequest request, HttpRequestBase method) throws UnsupportedEncodingException { if (request.getBasicAuthUser() != null && request.getBasicAuthPassword() != null) { setBasicAuthHeader(method, request.getBasicAuthUser(), request.getBasicAuthPassword()); } else if (this.solrUsername != null && this.solrPassword != null) { setBasicAuthHeader(method, this.solrUsername, this.solrPassword); } }
Example #20
Source File: HttpClientHelper.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
protected HttpResponse executeGetOrHead(HttpRequestBase method) throws IOException { HttpResponse httpResponse = performHttpRequest(method); // Consume content for non-successful, responses. This avoids the connection being left open. if (!wasSuccessful(httpResponse)) { EntityUtils.consume(httpResponse.getEntity()); return httpResponse; } return httpResponse; }
Example #21
Source File: HttpClientHelper.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
public HttpResponse performRequest(HttpRequestBase request) { String method = request.getMethod(); HttpResponse response; try { response = executeGetOrHead(request); } catch (IOException e) { throw new HttpRequestException(String.format("Could not %s '%s'.", method, request.getURI()), e); } return response; }
Example #22
Source File: ApacheHttpRequestFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private void addRequestConfig(final HttpRequestBase base, final SdkHttpRequest request, final ApacheHttpRequestConfig requestConfig) { int connectTimeout = saturatedCast(requestConfig.connectionTimeout().toMillis()); int connectAcquireTimeout = saturatedCast(requestConfig.connectionAcquireTimeout().toMillis()); RequestConfig.Builder requestConfigBuilder = RequestConfig .custom() .setConnectionRequestTimeout(connectAcquireTimeout) .setConnectTimeout(connectTimeout) .setSocketTimeout(saturatedCast(requestConfig.socketTimeout().toMillis())) .setLocalAddress(requestConfig.localAddress()); ApacheUtils.disableNormalizeUri(requestConfigBuilder); /* * Enable 100-continue support for PUT operations, since this is * where we're potentially uploading large amounts of data and want * to find out as early as possible if an operation will fail. We * don't want to do this for all operations since it will cause * extra latency in the network interaction. */ if (SdkHttpMethod.PUT == request.method() && requestConfig.expectContinueEnabled()) { requestConfigBuilder.setExpectContinueEnabled(true); } base.setConfig(requestConfigBuilder.build()); }
Example #23
Source File: GetFolder.java From data-prep with Apache License 2.0 | 5 votes |
private HttpRequestBase onExecute(final String id) { try { URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/folders/" + id); return new HttpGet(uriBuilder.build()); } catch (URISyntaxException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } }
Example #24
Source File: HttpRequestBuilderTests.java From vividus with Apache License 2.0 | 5 votes |
@Test void buildPostWithContent() throws HttpRequestBuildException, IOException { HttpRequestBase request = builder.withHttpMethod(HttpMethod.POST).withEndpoint(ENDPOINT).withContent(CONTENT) .build(); assertRequestWithContent(request, HttpMethod.POST.name(), ENDPOINT, CONTENT); }
Example #25
Source File: Export.java From data-prep with Apache License 2.0 | 5 votes |
/** * @param parameters the export parameters. * @return the request to perform. */ private HttpRequestBase onExecute(ExportParameters parameters) { try { final String parametersAsString = objectMapper.writerFor(ExportParameters.class).writeValueAsString(parameters); final HttpPost post = new HttpPost(transformationServiceUrl + "/apply"); post.setEntity(new StringEntity(parametersAsString, ContentType.APPLICATION_JSON)); return post; } catch (Exception e) { throw new TDPException(APIErrorCodes.UNABLE_TO_EXPORT_CONTENT, e); } }
Example #26
Source File: AsuraCommonsHttpclient.java From AsuraFramework with Apache License 2.0 | 5 votes |
/** * @param header * @param httpRequestBase */ private void handlerHeader(Map<String, String> header, HttpRequestBase httpRequestBase) { if (Check.isNullOrEmpty(header)) { return; } Iterator<String> iterator = header.keySet().iterator(); while (iterator.hasNext()) { String headerName = iterator.next(); httpRequestBase.addHeader(headerName, header.get(headerName)); } }
Example #27
Source File: HttpClientHelper.java From WeEvent with Apache License 2.0 | 5 votes |
public <T> BaseResponse<T> invokeCGI(HttpRequestBase request, TypeReference<BaseResponse<T>> typeReference) throws BrokerException { long requestStartTime = System.currentTimeMillis(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(this.timeout) .setSocketTimeout(this.timeout) .build(); request.setConfig(requestConfig); try (CloseableHttpResponse httpResponse = this.httpClient.execute(request)) { log.info("invokeCGI {} in {} millisecond, response:{}", request.getURI(), System.currentTimeMillis() - requestStartTime, httpResponse.getStatusLine().toString()); if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) { log.error("invokeCGI failed, request url:{}, msg:{}", request.getURI(), httpResponse.getStatusLine().toString()); throw new BrokerException(ErrorCode.HTTP_RESPONSE_FAILED); } if (null == httpResponse.getEntity()) { log.error("invokeCGI failed, httpResponse.getEntity is null, request url:{}", request.getURI()); throw new BrokerException(ErrorCode.HTTP_RESPONSE_ENTITY_EMPTY); } byte[] responseResult = EntityUtils.toByteArray(httpResponse.getEntity()); BaseResponse<T> baseResponse = JsonHelper.json2Object(responseResult, typeReference); if (ErrorCode.SUCCESS.getCode() != baseResponse.getCode()) { log.error("invokeCGI failed, request url:{}, msg:{}", request.getURI(), baseResponse.getMessage()); throw new BrokerException(baseResponse.getCode(), baseResponse.getMessage()); } return baseResponse; } catch (IOException e) { log.error("invokeCGI error, request url:{}", request.getURI(), e); throw new BrokerException(ErrorCode.HTTP_REQUEST_EXECUTE_ERROR); } }
Example #28
Source File: FindStep.java From data-prep with Apache License 2.0 | 5 votes |
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); } }
Example #29
Source File: PostRequest.java From r2m-plugin-android with Apache License 2.0 | 5 votes |
@Override protected HttpRequestBase getRequest(RequestModel requestModel) { HttpPost httpPost=new HttpPost(requestModel.getTestUrl()); try { httpPost.setEntity(new StringEntity(requestModel.getRequest(),"UTF-8")); } catch (Exception e) { } return httpPost; }
Example #30
Source File: CommonsDataLoader.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
protected void closeQuietly(HttpRequestBase httpRequest, CloseableHttpResponse httpResponse, CloseableHttpClient client) { try { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); Utils.closeQuietly(httpResponse); } } finally { Utils.closeQuietly(client); } }