Java Code Examples for org.apache.http.client.methods.HttpEntityEnclosingRequestBase#setEntity()

The following examples show how to use org.apache.http.client.methods.HttpEntityEnclosingRequestBase#setEntity() . 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: AbstractHttpClient.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 根据请求信息创建HttpEntityEnclosingRequestBase.
 *
 * @param cls     类型Class
 * @param url     URL
 * @param headers Http请求头信息
 * @param params  请求参数列表
 * @return HttpEntityEnclosingRequestBase
 */
protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url,
                                                          final Map<String, String> headers, final Map<String, String> params) {
    try {
        final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url);
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> entityBase.addHeader(key, value));
        }

        final List<NameValuePair> pairs = covertParams2Nvps(params);
        entityBase.setEntity(new UrlEncodedFormEntity(pairs, this.conf.getCharset()));
        return entityBase;
    } catch (final Throwable e) {
        throw new HttpClientInvokeException(e.getMessage(), e);
    }
}
 
Example 2
Source File: XmlRequest.java    From sndml3 with MIT License 6 votes vote down vote up
public XmlRequest(CloseableHttpClient client, URI uri, Document requestDoc) {
	super(client, uri, getMethod(requestDoc));
	this.requestDoc = requestDoc;
	logger.debug(Log.REQUEST, uri.toString());
	// if requestDoc is null then use GET
	// this is only applicable for WSDL
	if (method == HttpMethod.GET) {
		requestText = null;
		request = new HttpGet(uri);
	}
	// otherwise use POST
	else {
		requestText = XmlFormatter.format(requestDoc);	
		HttpEntity requestEntity = new StringEntity(requestText, ContentType.TEXT_XML);
		HttpEntityEnclosingRequestBase httpPost = new HttpPost(uri);
		httpPost.setEntity(requestEntity);
		request = httpPost;
	}		
}
 
Example 3
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 4
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload) {
  HttpResponse response = null;
  try {
    log(request);
    HttpClient httpclient = new DefaultHttpClient();
    request.setEntity(new ByteArrayEntity(payload));
    response = httpclient.execute(request);
    log(response);
  } catch(IOException ioe) {
    throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
  }
  return response;
}
 
Example 5
Source File: HttpClientStack.java    From android-discourse 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 6
Source File: HttpMetricNamesHandlerIntegrationTest.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("/metric_metadata/metrics/_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 7
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 8
Source File: HttpClientStack.java    From android_tv_metro 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 9
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 10
Source File: HttpClientStack.java    From simple_net_framework with MIT License 5 votes vote down vote up
/**
 * 将请求参数设置到HttpEntity中
 * 
 * @param httpRequest
 * @param request
 */
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example 11
Source File: HttpClientStack.java    From AndroidProjects with MIT License 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 12
Source File: ApacheHttpClientDelegate.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void setEntityIfGiven(HttpEntityEnclosingRequestBase request, Object entity) {
    if (entity != null) {
        if (entity instanceof File) {
            request.setEntity(new FileEntity((File) entity));
        } else {
            request.setEntity(new StringEntity((String) entity, Charset.defaultCharset()));
        }
    }
}
 
Example 13
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 14
Source File: ApacheHttpRequestFactory.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private HttpRequestBase wrapEntity(Request<?> request,
                                   HttpEntityEnclosingRequestBase entityEnclosingRequest,
                                   String encodedParams) throws FakeIOException {

    if (HttpMethodName.POST == request.getHttpMethod()) {
        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            entityEnclosingRequest.setEntity(ApacheUtils.newStringEntity(encodedParams));
        } else {
            entityEnclosingRequest.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
    } else {
        /*
         * We should never reuse the entity of the previous request, since
         * reading from the buffered entity will bypass reading from the
         * original request content. And if the content contains InputStream
         * wrappers that were added for validation-purpose (e.g.
         * Md5DigestCalculationInputStream), these wrappers would never be
         * read and updated again after AmazonHttpClient resets it in
         * preparation for the retry. Eventually, these wrappers would
         * return incorrect validation result.
         */
        if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get(HttpHeaders.CONTENT_LENGTH) == null) {
                entity = ApacheUtils.newBufferedHttpEntity(entity);
            }
            entityEnclosingRequest.setEntity(entity);
        }
    }
    return entityEnclosingRequest;
}
 
Example 15
Source File: HttpClientStack.java    From android-project-wo2b 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 16
Source File: RestClient.java    From nbp with Apache License 2.0 4 votes vote down vote up
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
    StringEntity entity = new StringEntity(body.toString(), "utf-8");
    req.setEntity(entity);
}
 
Example 17
Source File: OceanStor.java    From nbp with Apache License 2.0 4 votes vote down vote up
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
    StringEntity entity = new StringEntity(body.toString(), "utf-8");
    req.setEntity(entity);
}
 
Example 18
Source File: URIHandle.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Override
protected void receiveContent(InputStream content) {
  if (content == null) {
    return;
  }

  try {
    URI uri = get();
    if (uri == null) {
      throw new IllegalStateException("No uri for output");
    }

    HttpUriRequest method = null;
    HttpEntityEnclosingRequestBase receiver = null;
    if (isUsePut()) {
      HttpPut putter = new HttpPut(uri);
      method         = putter;
      receiver       = putter;
    } else {
      HttpPost poster = new HttpPost(uri);
      method          = poster;
      receiver        = poster;
    }

    InputStreamEntity entity = new InputStreamEntity(content, -1);

    receiver.setEntity(entity);

    HttpResponse response = client.execute(method, getContext());
    content.close();

    StatusLine status = response.getStatusLine();

    if (!method.isAborted()) {
      method.abort();
    }

    if (status.getStatusCode() >= 300) {
      throw new MarkLogicIOException("Could not write to "+uri.toString()+": "+status.getReasonPhrase());
    }
  } catch (IOException e) {
    throw new MarkLogicIOException(e);
  }
}
 
Example 19
Source File: RestClient.java    From nbp with Apache License 2.0 4 votes vote down vote up
@Override
public void setRequestBody(HttpEntityEnclosingRequestBase req, Object body) {
	StringEntity entity = new StringEntity(body.toString(), "utf-8");
	req.setEntity(entity);
}
 
Example 20
Source File: AsyncHttpClient.java    From Android-Basics-Codes with Artistic License 2.0 3 votes vote down vote up
/**
 * Perform a HTTP POST request and track the Android Context which initiated the request. Set
 * headers only for this request
 *
 * @param context         the Android Context which initiated the request.
 * @param url             the URL to send the request to.
 * @param headers         set headers only for this request
 * @param params          additional POST parameters to send with the request.
 * @param contentType     the content type of the payload you are sending, for example
 *                        application/json if sending a json payload.
 * @param responseHandler the response handler instance that should handle the response.
 * @return RequestHandle of future request process
 */
public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType,
                          ResponseHandlerInterface responseHandler) {
    HttpEntityEnclosingRequestBase request = new HttpPost(getURI(url));
    if (params != null) request.setEntity(paramsToEntity(params, responseHandler));
    if (headers != null) request.setHeaders(headers);
    return sendRequest(httpClient, httpContext, request, contentType,
            responseHandler, context);
}