本文整理汇总了Java中org.apache.http.client.entity.EntityBuilder类的典型用法代码示例。如果您正苦于以下问题:Java EntityBuilder类的具体用法?Java EntityBuilder怎么用?Java EntityBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
EntityBuilder类属于org.apache.http.client.entity包,在下文中一共展示了EntityBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: requestBuilderPost
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
/**
* XXX 通过RequestBuilder.post构造的post请求的formurlencoded编码有问题(使用了默认的ISO-8859-1, 应该采用UTF-8),
* 这会造成无法对中文参数进行正确的编码, 请使用setEntity来避免这个问题, 稍微丧失了RequestBuilder一点点易用性
*
* @return
*/
private String requestBuilderPost() {
HttpEntity entity = EntityBuilder.create()
.setContentType(ContentType.APPLICATION_FORM_URLENCODED.withCharset(Consts.UTF_8))
.setParameters(
new BasicNameValuePair("a", "1"),
new BasicNameValuePair("b", "中文test123")
).build();
HttpUriRequest request = RequestBuilder.post()
.setUri("http://www.baidu.com")
.addHeader("User-Agent", "A")
.addHeader("X-A", "AAA")
// .addParameter("a", "1")
// .addParameter("b", "中文test123")
.setEntity(entity) // 使用setEntity来避免默认的URL编码问题
.build();
return executeRequest(request, true);
}
示例2: HttpUtils
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
private HttpUtils(HttpRequestBase request) {
this.request = request;
this.clientBuilder = HttpClientBuilder.create();
this.isHttps = request.getURI().getScheme().equalsIgnoreCase("https");
this.config = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);
this.cookieStore = new BasicCookieStore();
if (request instanceof HttpPost) {
this.type = 1;
this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());
} else if (request instanceof HttpGet) {
this.type = 2;
this.uriBuilder = new URIBuilder();
} else if (request instanceof HttpPut) {
this.type = 3;
this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());
} else if (request instanceof HttpDelete) {
this.type = 4;
this.uriBuilder = new URIBuilder();
}
}
示例3: postStaticData
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
/**
* Posts static data, either as image or as file
*
* @param content the content
* @param isImage indicates whether this is an image or a file
* @return request object to check status codes and return values
*/
public Response postStaticData( final byte[ ] content, final boolean isImage )
{
final HttpPost request =
new HttpPost( this.yambasBase + "apps/" + this.appName + "/data/" + ( isImage ? "images/" : "files/" ) );
request.setEntity( EntityBuilder.create( ).setBinary( content ).build( ) );
request.addHeader( "Content-Type", "application/octet-stream" );
request.addHeader( "x-apiomat-apikey", this.apiKey );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
try
{
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例4: postRequestRestEndpoint
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
/**
* Sends a request to yambas base URL + path. yambas base URL is: yambasHost + "/yambas/rest/"
*
* @param path
* the path
* @param payLoad
* the payload as input stream
* @return request object to check status codes and return values
*/
public Response postRequestRestEndpoint( String path, InputStream payLoad )
{
final HttpPost request = new HttpPost( this.yambasBase + path );
setAuthorizationHeader( request );
request.addHeader( "ContentType", "application/json" );
request.addHeader( "x-apiomat-apikey", getApiKey( ) );
request.addHeader( "x-apiomat-system", getSystem( ).toString( ) );
try
{
request.setEntity( EntityBuilder.create( ).setStream( payLoad ).build( ) );
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例5: importCSVToApp
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
/**
* Imports a CSV dump into an existing app
*
* @param appName
* the Appname
* @param data
* payload of CSV-zip
*
* @return request object to check status codes and return values
*/
public Response importCSVToApp( String appName, InputStream data )
{
final HttpPost request = new HttpPost( this.yambasBase + "modules/csv/spec/" + appName );
setAuthorizationHeader( request );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
request.addHeader( "Content-Type", "application/octet-stream" );
request.addHeader( "X-apiomat-apikey", this.apiKey );
HttpEntity entity = EntityBuilder.create( ).setStream( data ).build( );
request.setEntity( entity );
try
{
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例6: test
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test
public void test() throws Exception {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPut put = new HttpPut(
String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER));
put.setEntity(EntityBuilder.create().setText(VALUE)
.setContentType(ContentType.create("text-plain", StandardCharsets.UTF_8)).build());
try (CloseableHttpResponse resp = client.execute(put)) {
assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode());
}
HttpGet get = new HttpGet(
String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER));
try (CloseableHttpResponse resp = client.execute(get)) {
assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode());
assertEquals("value",
Bytes.toString(ByteStreams.toByteArray(resp.getEntity().getContent())));
}
get = new HttpGet(String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), "whatever",
FAMILY, QUALIFIER));
try (CloseableHttpResponse resp = client.execute(get)) {
assertEquals(HttpStatus.SC_NOT_FOUND, resp.getStatusLine().getStatusCode());
}
}
}
示例7: Sender
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
public Sender(KhronusConfig config) {
this.hosts = config.getHosts();
this.endpoint = config.getEndpoint();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(config.getMaxConnections());
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager);
this.httpClient = builder.build();
this.responseHandler = new BasicResponseHandler();
this.requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
this.entityBuilder = EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).gzipCompress();
LOG.debug("Sender to send metrics created [Hosts: {}; MaxConnections: {}; socketTimeout: {}; connectionRequestTimeout: {}; connectTimeout: {}]",
config.getHosts(), config.getMaxConnections(), socketTimeout, connectionRequestTimeout, connectTimeout);
}
示例8: doPost
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
public String doPost(String url, String content) throws Exception {
CloseableHttpClient _httpClient = __doBuildHttpClient();
try {
_LOG.debug("Request URL [" + url + "] PostBody [" + content + "]");
String _result = _httpClient.execute(RequestBuilder.post()
.setUri(url)
.setEntity(EntityBuilder.create()
.setContentEncoding(DEFAULT_CHARSET)
.setContentType(ContentType.create("application/x-www-form-urlencoded", DEFAULT_CHARSET))
.setText(content).build()).build(), new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws IOException {
return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
}
});
_LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
return _result;
} finally {
_httpClient.close();
}
}
示例9: createShapefileBackedDataStore
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
public boolean createShapefileBackedDataStore(String workspaceName,
String dataStoreName, String filePath) throws Exception {
String geoserverHostAndPort = this.getGeoserverHostAndPort();
logger.debug("About to load data from [" + filePath
+ "] into data store [" + dataStoreName + "] in workspace ["
+ workspaceName + "]");
HttpPut request = new HttpPut("http://" + geoserverHostAndPort
+ "/geoserver/rest/workspaces/" + workspaceName
+ "/datastores/" + dataStoreName
+ "/file.shp?configure=all&target=shp");
request.addHeader("Content-type", "application/zip");
request.setEntity(EntityBuilder.create().setFile(new File(filePath))
.build());
return (Boolean) process(request, 201);
}
示例10: testCreateSuspect
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
public void testCreateSuspect() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
StringBuilder url = new StringBuilder(BASE_URL);
url.append("suspect/");
HttpPost httpPost = new HttpPost(url.toString());
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setContentType(ContentType.APPLICATION_JSON);
Suspect aaron = createMockSuspect("982c4a67-bb39-41f9-9872-88356822b7ad", "Aaron");
JsonHelper jsonHelper = new JsonHelper();
String jsonRequest = jsonHelper.convertToJson(aaron);
entityBuilder.setText(jsonRequest);
httpPost.setEntity(entityBuilder.build());
CloseableHttpResponse response = httpclient.execute(httpPost);
Assert.assertTrue(true);
}
示例11: testHttpPost
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test
public void testHttpPost() throws Exception {
URI postUri = new URIBuilder()
.setScheme("https")
.setHost(DOMAIN.split("//")[1])
.setPath("/datasync/id/" + UNITTEST_DATASET_ID)
.build();
InputStream is = new FileInputStream(new File("src/test/resources/example_patch.sdiff"));
byte[] data = IOUtils.toByteArray(is);
HttpEntity entity = EntityBuilder.create().setBinary(data).build();
try(CloseableHttpResponse response = http.post(postUri, entity);
InputStream body = response.getEntity().getContent()) {
// uncomment the test below, when di2 is running in prod
/*
TestCase.assertEquals(201, response.getStatusLine().getStatusCode());
String blobId = mapper.readValue(response.getEntity().getContent(), BlobId.class).blobId;
TestCase.assertNotNull(blobId);
*/
}
}
示例12: testExecRequestRetryOnAuthChallenge
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test
public void testExecRequestRetryOnAuthChallenge() throws Exception {
final HttpRoute route = new HttpRoute(target);
final HttpClientContext context = new HttpClientContext();
final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
response1.setEntity(EntityBuilder.create()
.setStream(instream1)
.build());
final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4}));
response2.setEntity(EntityBuilder.create()
.setStream(instream2)
.build());
Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
Mockito.when(requestExecutor.execute(
Mockito.same(request),
Mockito.<HttpClientConnection>any(),
Mockito.<HttpClientContext>any())).thenReturn(response1, response2);
Mockito.when(reuseStrategy.keepAlive(
Mockito.<HttpResponse>any(),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
Mockito.when(targetAuthStrategy.isAuthenticationRequested(
Mockito.eq(target),
Mockito.same(response1),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
final CloseableHttpResponse finalResponse = mainClientExec.execute(
route, request, context, execAware);
Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context);
Mockito.verify(instream1).close();
Mockito.verify(instream2, Mockito.never()).close();
Assert.assertNotNull(finalResponse);
Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode());
}
示例13: testEstablishRouteViaProxyTunnelRetryOnAuthChallengePersistentConnection
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test
public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengePersistentConnection() throws Exception {
final AuthState authState = new AuthState();
final HttpRoute route = new HttpRoute(target, null, proxy, true);
final HttpClientContext context = new HttpClientContext();
final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
response1.setEntity(EntityBuilder.create()
.setStream(instream1)
.build());
final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
Mockito.when(proxyAuthStrategy.isAuthenticationRequested(
Mockito.eq(proxy),
Mockito.same(response1),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
Mockito.when(reuseStrategy.keepAlive(
Mockito.<HttpResponse>any(),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
Mockito.when(requestExecutor.execute(
Mockito.<HttpRequest>any(),
Mockito.<HttpClientConnection>any(),
Mockito.<HttpClientContext>any())).thenReturn(response1, response2);
mainClientExec.establishRoute(authState, managedConn, route, request, context);
Mockito.verify(connManager).connect(managedConn, route, 0, context);
Mockito.verify(connManager).routeComplete(managedConn, route, context);
Mockito.verify(instream1).close();
}
示例14: testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test
public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection() throws Exception {
final AuthState authState = new AuthState();
final HttpRoute route = new HttpRoute(target, null, proxy, true);
final HttpClientContext context = new HttpClientContext();
final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
response1.setEntity(EntityBuilder.create()
.setStream(instream1)
.build());
final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
Mockito.when(proxyAuthStrategy.isAuthenticationRequested(
Mockito.eq(proxy),
Mockito.same(response1),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
Mockito.when(reuseStrategy.keepAlive(
Mockito.<HttpResponse>any(),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.FALSE);
Mockito.when(requestExecutor.execute(
Mockito.<HttpRequest>any(),
Mockito.<HttpClientConnection>any(),
Mockito.<HttpClientContext>any())).thenReturn(response1, response2);
mainClientExec.establishRoute(authState, managedConn, route, request, context);
Mockito.verify(connManager).connect(managedConn, route, 0, context);
Mockito.verify(connManager).routeComplete(managedConn, route, context);
Mockito.verify(instream1, Mockito.never()).close();
Mockito.verify(managedConn).close();
}
示例15: testRedirectProtocolException
import org.apache.http.client.entity.EntityBuilder; //导入依赖的package包/类
@Test(expected = ProtocolException.class)
public void testRedirectProtocolException() throws Exception {
final HttpRoute route = new HttpRoute(target);
final HttpGet get = new HttpGet("/test");
final HttpRequestWrapper request = HttpRequestWrapper.wrap(get);
final HttpClientContext context = HttpClientContext.create();
final CloseableHttpResponse response1 = Mockito.mock(CloseableHttpResponse.class);
final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
final HttpEntity entity1 = EntityBuilder.create()
.setStream(instream1)
.build();
Mockito.when(response1.getEntity()).thenReturn(entity1);
Mockito.when(requestExecutor.execute(
Mockito.eq(route),
Mockito.same(request),
Mockito.<HttpClientContext>any(),
Mockito.<HttpExecutionAware>any())).thenReturn(response1);
Mockito.when(redirectStrategy.isRedirected(
Mockito.same(get),
Mockito.same(response1),
Mockito.<HttpClientContext>any())).thenReturn(Boolean.TRUE);
Mockito.doThrow(new ProtocolException("Oppsie")).when(redirectStrategy).getRedirect(
Mockito.same(get),
Mockito.same(response1),
Mockito.<HttpClientContext>any());
try {
redirectExec.execute(route, request, context, execAware);
} catch (final Exception ex) {
Mockito.verify(instream1).close();
Mockito.verify(response1).close();
throw ex;
}
}