当前位置: 首页>>代码示例>>Java>>正文


Java BasicHttpEntity类代码示例

本文整理汇总了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());
	}
}
 
开发者ID:swxiao,项目名称:bubble2,代码行数:23,代码来源:ResponseWrap.java

示例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());
    }
}
 
开发者ID:rpgreen,项目名称:apigateway-generic-java-sdk,代码行数:27,代码来源:GenericApiGatewayClientTest.java

示例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;
}
 
开发者ID:pooyafaroka,项目名称:PlusGram,代码行数:20,代码来源:HurlStack.java

示例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);
		}

	}
 
开发者ID:RestComm,项目名称:camelgateway,代码行数:17,代码来源:CamelGatewaySbb.java

示例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;
    }
}
 
开发者ID:Espenhh,项目名称:panopticon,代码行数:25,代码来源:PanopticonClient.java

示例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;
}
 
开发者ID:jkiddo,项目名称:ccow,代码行数:25,代码来源:RequestHandlerUtil.java

示例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");
}
 
开发者ID:testmycode,项目名称:tmc-cli,代码行数:17,代码来源:TmcUtilTest.java

示例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);
}
 
开发者ID:vespa-engine,项目名称:vespa,代码行数:23,代码来源:ConfigServerHttpRequestExecutorTest.java

示例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;
}
 
开发者ID:CaMnter,项目名称:SaveVolley,代码行数:27,代码来源:HurlStack.java

示例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());
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:24,代码来源:TestBasicHttpCache.java

示例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());
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:21,代码来源:TestDefaultRedirectStrategy.java

示例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;
}
 
开发者ID:wso2,项目名称:carbon-device-mgt,代码行数:17,代码来源:AuthenticationHandlerTest.java

示例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;
}
 
开发者ID:himanshuagarwal77225,项目名称:BookMySkills,代码行数:24,代码来源:ExtHttpClientStack.java

示例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;
}
 
开发者ID:himanshuagarwal77225,项目名称:BookMySkills,代码行数:26,代码来源:HurlStack.java

示例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();
    }
 
开发者ID:cytomine,项目名称:Cytomine-client-autobuilder,代码行数:22,代码来源:HttpClient.java


注:本文中的org.apache.http.entity.BasicHttpEntity类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。