本文整理汇总了Java中org.apache.http.entity.BasicHttpEntity类的典型用法代码示例。如果您正苦于以下问题:Java BasicHttpEntity类的具体用法?Java BasicHttpEntity怎么用?Java BasicHttpEntity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BasicHttpEntity类属于org.apache.http.entity包,在下文中一共展示了BasicHttpEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: ResponseWrap
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context,
ObjectMapper _mapper) {
this.response = response;
this.httpClient = httpClient;
this.request = request;
this.context = context;
mapper = _mapper;
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
this.entity = new BufferedHttpEntity(entity);
} else {
this.entity = new BasicHttpEntity();
}
EntityUtils.consumeQuietly(entity);
this.response.close();
} catch (IOException e) {
logger.warn(e.getMessage());
}
}
示例2: testExecute_non2xx_exception
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
@Test
public void testExecute_non2xx_exception() throws IOException {
HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
resp.setEntity(entity);
Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));
Map<String, String> headers = new HashMap<>();
headers.put("Account-Id", "fubar");
headers.put("Content-Type", "application/json");
try {
client.execute(
new GenericApiGatewayRequestBuilder()
.withBody(new ByteArrayInputStream("test request".getBytes()))
.withHttpMethod(HttpMethodName.POST)
.withHeaders(headers)
.withResourcePath("/test/orders").build());
Assert.fail("Expected exception");
} catch (GenericApiGatewayException e) {
assertEquals("Wrong status code", 404, e.getStatusCode());
assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
}
}
示例3: entityFromConnection
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
/**
* Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
* @param connection
* @return an HttpEntity populated with data from <code>connection</code>.
*/
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
示例4: pushContent
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
private void pushContent(HttpUriRequest request, String contentType, String contentEncoding, byte[] content) {
// TODO: check other preconditions?
if (contentType != null && content != null && request instanceof HttpEntityEnclosingRequest) {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(content));
entity.setContentLength(content.length);
entity.setChunked(false);
if (contentEncoding != null)
entity.setContentEncoding(contentEncoding);
entity.setContentType(contentType);
HttpEntityEnclosingRequest rr = (HttpEntityEnclosingRequest) request;
rr.setEntity(entity);
}
}
示例5: sendMeasurementsToPanopticon
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
boolean sendMeasurementsToPanopticon(Status status) {
try {
String json = OBJECT_MAPPER.writeValueAsString(status);
String uri = baseUri + "/external/status";
LOG.debug("Updating status: " + uri);
LOG.debug("...with JSON: " + json);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(json.getBytes()));
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json");
try (CloseableHttpResponse response = client.execute(httpPost)) {
LOG.debug("Response: " + response.getStatusLine().getStatusCode());
return response.getStatusLine().getStatusCode() < 300;
}
} catch (IOException e) {
LOG.warn("Error when updating status", e);
return false;
}
}
示例6: responseToEntity
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
public static BasicHttpEntity responseToEntity(final Response jerseyResponse) throws UnsupportedEncodingException {
final BasicHttpEntity entity = new BasicHttpEntity();
if (jerseyResponse.getEntity() != null) {
// com.sun.jersey.core.impl.provider.entity.BaseFormProvider
final String charsetName = "UTF-8";
final Form t = (Form) jerseyResponse.getEntity();
final StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> e : t.entrySet()) {
for (final String value : e.getValue()) {
if (sb.length() > 0)
sb.append('&');
sb.append(URLEncoder.encode(e.getKey(), charsetName));
if (value != null) {
sb.append('=');
sb.append(URLEncoder.encode(value, charsetName));
}
}
}
entity.setContent(new ByteArrayInputStream(sb.toString().getBytes()));
entity.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
return entity;
}
示例7: loginCatchesFailedHttpResponseException
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
@Test
public void loginCatchesFailedHttpResponseException() {
Callable<List<Course>> callable =
new Callable<List<Course>>() {
@Override
public List<Course> call() throws Exception {
Exception exception =
new FailedHttpResponseException(401, new BasicHttpEntity());
throw new Exception(exception);
}
};
when(mockCore.listCourses(any(ProgressObserver.class))).thenReturn(callable);
TmcUtil.tryToLogin(ctx, new Account());
io.assertContains("Incorrect username or password");
}
示例8: initExecutor
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
@Before
public void initExecutor() throws IOException {
SelfCloseableHttpClient httpMock = mock(SelfCloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" ");
if (mockReturnCode == 100000) throw new RuntimeException("FAIL");
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
BasicHttpEntity entity = new BasicHttpEntity();
String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
entity.setContent(stream);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getEntity()).thenReturn(entity);
when(response.getStatusLine()).thenReturn(statusLine);
return response;
});
executor = new ConfigServerHttpRequestExecutor(configServers, httpMock);
}
示例9: entityFromConnection
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
/**
* Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
*
* @return an HttpEntity populated with data from <code>connection</code>.
*/
/*
* 通过一个 HttpURLConnection 获取其对应的 HttpEntity ( 这里就 HttpEntity 而言,耦合了 Apache )
*/
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
// 设置 HttpEntity 的内容
entity.setContent(inputStream);
// 设置 HttpEntity 的长度
entity.setContentLength(connection.getContentLength());
// 设置 HttpEntity 的编码
entity.setContentEncoding(connection.getContentEncoding());
// 设置 HttpEntity Content-Type
entity.setContentType(connection.getContentType());
return entity;
}
示例10: testOriginalResponseWithNoContentSizeHeaderIsReleased
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
@Test
public void testOriginalResponseWithNoContentSizeHeaderIsReleased() throws Exception {
final HttpHost host = new HttpHost("foo.example.com");
final HttpRequest request = new HttpGet("http://foo.example.com/bar");
final Date now = new Date();
final Date requestSent = new Date(now.getTime() - 3 * 1000L);
final Date responseGenerated = new Date(now.getTime() - 2 * 1000L);
final Date responseReceived = new Date(now.getTime() - 1 * 1000L);
final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
final BasicHttpEntity entity = new BasicHttpEntity();
final ConsumableInputStream inputStream = new ConsumableInputStream(new ByteArrayInputStream(HttpTestUtils.getRandomBytes(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)));
entity.setContent(inputStream);
originResponse.setEntity(entity);
originResponse.setHeader("Cache-Control","public, max-age=3600");
originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated));
originResponse.setHeader("ETag", "\"etag\"");
final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived);
IOUtils.consume(result.getEntity());
assertTrue(inputStream.wasClosed());
}
示例11: testGetRedirectRequestForTemporaryRedirect
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
@Test
public void testGetRedirectRequestForTemporaryRedirect() throws Exception {
final DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
HttpStatus.SC_TEMPORARY_REDIRECT, "Temporary Redirect");
response.addHeader("Location", "http://localhost/stuff");
final HttpContext context1 = new BasicHttpContext();
final HttpUriRequest redirect1 = redirectStrategy.getRedirect(
new HttpTrace("http://localhost/"), response, context1);
Assert.assertEquals("TRACE", redirect1.getMethod());
final HttpContext context2 = new BasicHttpContext();
final HttpPost httppost = new HttpPost("http://localhost/");
final HttpEntity entity = new BasicHttpEntity();
httppost.setEntity(entity);
final HttpUriRequest redirect2 = redirectStrategy.getRedirect(
httppost, response, context2);
Assert.assertEquals("POST", redirect2.getMethod());
Assert.assertTrue(redirect2 instanceof HttpEntityEnclosingRequest);
Assert.assertSame(entity, ((HttpEntityEnclosingRequest) redirect2).getEntity());
}
示例12: getValidationResponse
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException {
ValidationResponce response = new ValidationResponce();
response.setDeviceId("1234");
response.setDeviceType("testdevice");
response.setJWTToken("1234567788888888");
response.setTenantId(-1234);
Gson gson = new Gson();
String jsonReponse = gson.toJson(response);
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
return mockDCRResponse;
}
示例13: convertEntityNewToOld
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
private org.apache.http.HttpEntity convertEntityNewToOld(HttpEntity ent) throws IllegalStateException, IOException
{
BasicHttpEntity ret = new BasicHttpEntity();
if (ent != null)
{
ret.setContent(ent.getContent());
ret.setContentLength(ent.getContentLength());
Header h;
h = ent.getContentEncoding();
if (h != null)
{
ret.setContentEncoding(convertheaderNewToOld(h));
}
h = ent.getContentType();
if (h != null)
{
ret.setContentType(convertheaderNewToOld(h));
}
}
return ret;
}
示例14: entityFromConnection
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
/**
* Initializes an {@link HttpEntity} from the given
* {@link HttpURLConnection}.
*
* @param connection
* @return an HttpEntity populated with data from <code>connection</code>.
*/
private static HttpEntity entityFromConnection(HttpURLConnection connection)
{
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try
{
inputStream = connection.getInputStream();
}
catch (IOException ioe)
{
inputStream = connection.getErrorStream();
}
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
示例15: postCookie
import org.apache.http.entity.BasicHttpEntity; //导入依赖的package包/类
public int postCookie(String data) throws Exception {
HttpPost httpPost = new HttpPost(URL.toString());
System.out.println("change user agent");
HttpContext HTTP_CONTEXT = new BasicHttpContext();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
HTTP_CONTEXT.setAttribute(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
if (isAuthByPrivateKey) httpPost.setHeaders(headersArray);
// httpPost.addHeader("Content-Type","application/json")
// httpPost.addHeader("host",this.host)
log.debug("Post send :" + data.replace("\n", ""));
//write data
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(data.getBytes()));
entity.setContentLength((long)data.getBytes().length);
httpPost.setEntity(entity);
response = client.execute(targetHost, httpPost, localcontext);
return response.getStatusLine().getStatusCode();
}