org.apache.http.client.methods.HttpEntityEnclosingRequestBase Java Examples

The following examples show how to use org.apache.http.client.methods.HttpEntityEnclosingRequestBase. 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: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = HttpClientBuilder.create().build();

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);

    BasicHttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(HttpClientContext.COOKIE_STORE, getWebDriverCookies(driver.manage().getCookies()));
    requestMethod.setHeader("User-Agent", getWebDriverUserAgent());

    if (null != urlParameters && (
            httpRequestMethod.equals(RequestType.PATCH) ||
                    httpRequestMethod.equals(RequestType.POST) ||
                    httpRequestMethod.equals(RequestType.PUT))
            ) {
        ((HttpEntityEnclosingRequestBase) requestMethod).setEntity(new UrlEncodedFormEntity(urlParameters));
    }

    return client.execute(requestMethod, localContext);
}
 
Example #2
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void log(HttpEntityEnclosingRequestBase request)  {
  if (logger != null) {
    List<String> headers = new ArrayList<>();
    for (Header h : request.getAllHeaders()) {
      headers.add(h.toString());
    }
    byte[] cnt = null;
    InputStream s;
    try {
      s = request.getEntity().getContent();
      cnt = IOUtils.toByteArray(s);
      s.close();
    } catch (Exception e) {
    }
    logger.logRequest(request.getMethod(), request.getURI().toString(), headers, cnt);
  }    
}
 
Example #3
Source File: HttpClient.java    From aliyun-tsdb-java-sdk with Apache License 2.0 6 votes vote down vote up
public static HttpResponse redirectResponse(HttpResponse httpResponse,
                                            HttpEntityEnclosingRequestBase request,
                                            CloseableHttpAsyncClient httpclient)
        throws ExecutionException, InterruptedException {
    HttpResponse result = null;

    Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
    for (Header header : headers) {
        if (header.getName().equalsIgnoreCase(HttpHeaders.LOCATION)) {
            String newUrl = header.getValue();
            request.setURI(URI.create(newUrl));
            Future<HttpResponse> future = httpclient.execute(request, null);
            result = future.get();
            break;
        }
    }
    if (result == null) {
        return httpResponse;
    }
    return result;
}
 
Example #4
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example #5
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
 protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
	HttpResponse response = null;
	boolean ok = false;
	int tryCount = 0;
	while (!ok) {
	try {
	    tryCount++;
		HttpClient httpclient = new DefaultHttpClient();
		if(proxy != null) {
			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		}
		request.setEntity(new ByteArrayEntity(payload));
     log(request);
		response = httpclient.execute(request);
	    ok = true;
	} catch(IOException ioe) {
	    if (tryCount <= retryCount) {
	      ok = false;
	    } else {
		throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
	}
	  }
	}
	return response;
}
 
Example #6
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void log(HttpEntityEnclosingRequestBase request)  {
  if (logger != null) {
    List<String> headers = new ArrayList<>();
    for (Header h : request.getAllHeaders()) {
      headers.add(h.toString());
    }
    byte[] cnt = null;
    InputStream s;
    try {
      s = request.getEntity().getContent();
      cnt = IOUtils.toByteArray(s);
      s.close();
    } catch (Exception e) {
    }
    logger.logRequest(request.getMethod(), request.getURI().toString(), headers, cnt);
  }    
}
 
Example #7
Source File: ODataEntityUpdateRequestImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataEntityUpdateResponse<E> execute() {
  final InputStream input = getPayload();
  ((HttpEntityEnclosingRequestBase) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input));

  try {
    final HttpResponse httpResponse = doExecute();
    final ODataEntityUpdateResponseImpl response =
            new ODataEntityUpdateResponseImpl(odataClient, httpClient, httpResponse);
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
      response.close();
    }
    return response;
  } finally {
    IOUtils.closeQuietly(input);
  }
}
 
Example #8
Source File: VrApacheClient.java    From verano-http with MIT License 6 votes vote down vote up
@Override
public final CloseableHttpResponse execute(
    final Dict request
) throws IOException {
    final HttpEntityEnclosingRequestBase base =
        new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                //@checkstyle RequireThisCheck (1 lines)
                return new Method.Of(request).asString();
            }
        };
    final URI uri = new RequestUri.Of(request).uri();
    base.setConfig(this.config);
    base.setURI(uri);
    base.setEntity(new StringEntity(new Body.Of(request).asString()));
    for (final Kvp header : new Headers.Of(request)) {
        base.addHeader(header.key(), header.value());
    }
    return this.origin.get().execute(base);
}
 
Example #9
Source File: ResultErrorHandler.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
protected void doHandle(String uriId,HttpUriRequest request,Object result){
	if(this.isError(result)){
		String content = null;
		if(request instanceof HttpEntityEnclosingRequestBase){
			HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request;
			HttpEntity entity = request_base.getEntity();
			//MULTIPART_FORM_DATA 请求类型判断
			if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){
				try {
					content = EntityUtils.toString(entity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(logger.isErrorEnabled()){
				logger.error("URI[{}] {} Content:{} Result:{}",
						uriId,
						request.getURI(),
						content == null ? "multipart_form_data" : content,
						result == null? null : JsonUtil.toJSONString(result));
			}
		}
		this.handle(uriId,request.getURI().toString(),content,result);
	}
}
 
Example #10
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example #11
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void log(HttpEntityEnclosingRequestBase request)  {
  if (logger != null) {
    List<String> headers = new ArrayList<>();
    for (Header h : request.getAllHeaders()) {
      headers.add(h.toString());
    }
    byte[] cnt = null;
    InputStream s;
    try {
      s = request.getEntity().getContent();
      cnt = IOUtils.toByteArray(s);
      s.close();
    } catch (Exception e) {
    }
    logger.logRequest(request.getMethod(), request.getURI().toString(), headers, cnt);
  }    
}
 
Example #12
Source File: ProtobufSpringEncoderTest.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
		throws IOException, URISyntaxException {
	final List<HttpUriRequest> request = new ArrayList<>(1);
	BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any()))
			.will(new Answer<HttpResponse>() {
				@Override
				public HttpResponse answer(InvocationOnMock invocationOnMock)
						throws Throwable {
					request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
					return new BasicHttpResponse(new BasicStatusLine(
							new ProtocolVersion("http", 1, 1), 200, null));
				}
			});
	new ApacheHttpClient(this.httpClient).execute(
			requestTemplate.resolve(new HashMap<>()).request(),
			new feign.Request.Options());
	HttpUriRequest httpUriRequest = request.get(0);
	return ((HttpEntityEnclosingRequestBase) httpUriRequest).getEntity();
}
 
Example #13
Source File: ActionRunner.java    From curly with Apache License 2.0 6 votes vote down vote up
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException {
    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    List<NameValuePair> formParams = new ArrayList<>();
    postVariables.forEach((name, values) -> values.forEach(value -> {
        if (multipart) {
            if (value.startsWith("@")) {
                File f = new File(value.substring(1));
                multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName());
            } else {
                multipartBuilder.addTextBody(name, value);
            }
        } else {
            formParams.add(new BasicNameValuePair(name, value));
        }
    }));
    if (multipart) {
        request.setEntity(multipartBuilder.build());
    } else {
        request.setEntity(new UrlEncodedFormEntity(formParams));
    }
}
 
Example #14
Source File: ApacheHttpClient4Signer.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
public void sign(HttpRequestBase req) throws IOException {
  String payload = null;
  Charset charset = Charset.defaultCharset();
  if (HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())) {
    HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) req;
    HttpEntity entity = requestBase.getEntity();
    if (entity.getContentLength() > 0) {
      if (!entity.isRepeatable()) {
        throw new IOException(
            "The signer needs to read the request payload but the input stream of this request cannot be read multiple times. Please provide the payload using a separate argument or ensure that the entity is repeatable.");
      }
      ContentType contentType = ContentType.get(entity);
      charset = contentType.getCharset();
      payload = EntityUtils.toString(entity, contentType.getCharset());
    }
  }

  String authHeader = OAuth.getAuthorizationHeader(req.getURI(), req.getMethod(), payload, charset, consumerKey, signingKey);
  req.setHeader(OAuth.AUTHORIZATION_HEADER_NAME, authHeader);
}
 
Example #15
Source File: EventElasticSearchIOTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownClass() throws Exception {
    URIBuilder builder = new URIBuilder().setScheme("http")
            .setHost("127.0.0.1").setPort(9200)
            .setPath("/events/graphite_event/_query");

    HttpEntityEnclosingRequestBase delete = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return "DELETE";
        }
    };
    delete.setURI(builder.build());

    String deletePayload = "{\"query\":{\"match_all\":{}}}";
    HttpEntity entity = new NStringEntity(deletePayload, ContentType.APPLICATION_JSON);
    delete.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(delete);
    if(response.getStatusLine().getStatusCode() != 200)
    {
        System.out.println("Couldn't delete index after running tests.");
    }
    else {
        System.out.println("Successfully deleted index after running tests.");
    }
}
 
Example #16
Source File: HttpClientStack.java    From product-emm with Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #17
Source File: ElasticIOIntegrationTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
private void deleteAllDocuments(String typeToEmpty) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder().setScheme("http")
            .setHost("127.0.0.1").setPort(9200)
            .setPath(typeToEmpty);

    HttpEntityEnclosingRequestBase delete = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return "DELETE";
        }
    };
    delete.setURI(builder.build());

    String deletePayload = "{\"query\":{\"match_all\":{}}}";
    HttpEntity entity = new NStringEntity(deletePayload, ContentType.APPLICATION_JSON);
    delete.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(delete);
    if(response.getStatusLine().getStatusCode() != 200)
    {
        System.out.println(String.format("Couldn't delete index [%s] after running tests.", typeToEmpty));
    }
    else {
        System.out.println(String.format("Successfully deleted [%s] index after running tests.", typeToEmpty));
    }
}
 
Example #18
Source File: HttpClientStack.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #19
Source File: ApacheHttpStack.java    From jus with Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
                                            Request<?> request) {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #20
Source File: AbstractRestClient.java    From jea with Apache License 2.0 5 votes vote down vote up
protected Object transferWS(String methodName, Object... params) throws Exception {
HttpRequestBase request = getMethod(getUrl(methodName, params));

if(request instanceof HttpEntityEnclosingRequestBase){
	HttpEntity entity = getHttpEntity(params);
	if(entity != null){
		((HttpEntityEnclosingRequestBase)request).setEntity(entity);
	}
}

CloseableHttpResponse response = null;
try{
    response = client.execute(request);
    if(response.getStatusLine().getStatusCode() == 200){
    	return EntityUtils.toString(response.getEntity());
    } else {
    	if(response.getStatusLine().getStatusCode() == 204){
    		//使用REST时,如果返回结果是void时,此时Http的返回码是204
    		//HTTP的204(No Content)响应,就表示执行成功,但是服务器没有返回数据.
    		return "";
    	} else {
    		throw new Exception("调用服务失败,返回结果码为" + response.getStatusLine().getStatusCode());
		}
    }
   	
} finally {
	client.close();
	if(response != null){
		response.close();
	}
}

  }
 
Example #21
Source File: HttpJsonDataUtils.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #22
Source File: AsyncHttpClient.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for
 * example not DELETE
 *
 * @param entity      entity to be included within the request
 * @param requestBase HttpRequest instance, must not be null
 */
private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
    if (entity != null) {
        requestBase.setEntity(entity);
    }

    return requestBase;
}
 
Example #23
Source File: AsyncHttpClient.java    From Libraries-for-Android-Developers with MIT License 5 votes vote down vote up
/**
 * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for
 * example not DELETE
 *
 * @param entity      entity to be included within the request
 * @param requestBase HttpRequest instance, must not be null
 */
private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
    if (entity != null) {
        requestBase.setEntity(entity);
    }

    return requestBase;
}
 
Example #24
Source File: AsyncHttpClient.java    From letv with Apache License 2.0 5 votes vote down vote up
public void post(Context context, String url, Header[] headers, RequestParams params, String contentType, AsyncHttpResponseHandler responseHandler) {
    HttpEntityEnclosingRequestBase request = new HttpPost(url);
    if (params != null) {
        request.setEntity(paramsToEntity(params));
    }
    if (headers != null) {
        request.setHeaders(headers);
    }
    sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context);
}
 
Example #25
Source File: ConanResourceITSupport.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
private Response execute(HttpEntityEnclosingRequestBase request) throws Exception {
  try (CloseableHttpResponse response = clientBuilder().build().execute(request)) {
    ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
    Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
    }
    return responseBuilder.build();
  }
}
 
Example #26
Source File: AbstractHttpClient.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 根据请求信息创建HttpEntityEnclosingRequestBase.
 *
 * @param cls         类型Class
 * @param url         URL
 * @param stream      流式报文
 * @param contentType 报文类型
 * @return HttpEntityEnclosingRequestBase
 */
protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url,
                                                          final String stream, final ContentType contentType) {
    try {
        final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url);
        entityBase.setEntity(new StringEntity(stream, contentType));
        return entityBase;
    } catch (final Throwable e) {
        throw new HttpClientInvokeException(e.getMessage(), e);
    }
}
 
Example #27
Source File: P2ResourceITSupport.java    From nexus-repository-p2 with Eclipse Public License 1.0 5 votes vote down vote up
private void prepareRequest(HttpEntityEnclosingRequestBase request, String url, Object body) throws Exception {
  request.setEntity(new ByteArrayEntity(OBJECT_MAPPER.writeValueAsBytes(body), ContentType.APPLICATION_JSON));
  UriBuilder uriBuilder = UriBuilder.fromUri(nexusUrl.toString()).path(url);
  request.setURI(uriBuilder.build());
  String auth = credentials.getUserName() + ":" + credentials.getPassword();
  request.setHeader(HttpHeaders.AUTHORIZATION,
      "Basic " + new String(Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8))));
}
 
Example #28
Source File: ResourceITSupport.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
private Response execute(HttpEntityEnclosingRequestBase request) throws Exception {
  try (CloseableHttpResponse response = clientBuilder().build().execute(request)) {
    ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
    Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
    }
    return responseBuilder.build();
  }
}
 
Example #29
Source File: HttpClientStack.java    From volley with Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(
        HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #30
Source File: HttpEventsQueryHandlerIntegrationTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownClass() throws Exception {
    URIBuilder builder = new URIBuilder().setScheme("http")
            .setHost("127.0.0.1").setPort(9200)
            .setPath("/events/graphite_event/_query");

    HttpEntityEnclosingRequestBase delete = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return "DELETE";
        }
    };
    delete.setURI(builder.build());

    String deletePayload = "{\"query\":{\"match_all\":{}}}";
    HttpEntity entity = new NStringEntity(deletePayload, ContentType.APPLICATION_JSON);
    delete.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(delete);
    if(response.getStatusLine().getStatusCode() != 200)
    {
        System.out.println("Couldn't delete index after running tests.");
    }
    else {
        System.out.println("Successfully deleted index after running tests.");
    }
}