當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。