Java 类org.apache.http.entity.BasicHttpEntity 实例源码
项目:bubble2
文件:ResponseWrap.java
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());
}
}
项目:apigateway-generic-java-sdk
文件:GenericApiGatewayClientTest.java
@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());
}
}
项目:camelgateway
文件:CamelGatewaySbb.java
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);
}
}
项目:panopticon
文件:PanopticonClient.java
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;
}
}
项目:ccow
文件:RequestHandlerUtil.java
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;
}
项目:tmc-cli
文件:TmcUtilTest.java
@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");
}
项目:vespa
文件:ConfigServerHttpRequestExecutorTest.java
@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);
}
项目:SaveVolley
文件:HurlStack.java
/**
* 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;
}
项目:purecloud-iot
文件:TestBasicHttpCache.java
@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());
}
项目:purecloud-iot
文件:TestDefaultRedirectStrategy.java
@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());
}
项目:carbon-device-mgt
文件:AuthenticationHandlerTest.java
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;
}
项目:BookMySkills
文件:ExtHttpClientStack.java
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;
}
项目:BookMySkills
文件:HurlStack.java
/**
* 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;
}
项目:Cytomine-client-autobuilder
文件:HttpClient.java
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();
}
项目:oldSyncopeIdM
文件:HttpResourceStream.java
private HttpResponse buildFakeResponse(final String errorMessage) {
ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(bais);
entity.setContentLength(0);
entity.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
BasicHttpResponse response = new BasicHttpResponse(
new ProtocolVersion("HTTP", 1, 1), 400,
"Exception: " + errorMessage);
response.setEntity(entity);
response.addHeader("Content-Disposition", "attachment; filename=error");
return response;
}
项目:AndroidLife
文件:HurlStack.java
/**
* 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;
}
项目:WeGit
文件:HttpKnife.java
/**
* 获取响应报文实体
*
* @return
* @throws IOException
*/
private HttpEntity entityFromConnection() throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
if (GZIP.equals(getResponseheader(ResponseHeader.HEADER_CONTENT_ENCODING))) {
entity.setContent(new GZIPInputStream(inputStream));
} else {
entity.setContent(inputStream);
}
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
项目:GitKnife
文件:HttpKnife.java
/**
* Get response
*
* @return
* @throws IOException
*/
private HttpEntity entityFromConnection() throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
if (GZIP.equals(getResponseheader(ResponseHeader.HEADER_CONTENT_ENCODING))) {
entity.setContent(new GZIPInputStream(inputStream));
} else {
entity.setContent(inputStream);
}
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
项目:simple_net_framework
文件:HttpUrlConnStack.java
/**
* 执行HTTP请求之后获取到其数据流,即返回请求结果的流
*
* @param connection
* @return
*/
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
inputStream = connection.getErrorStream();
}
// TODO : GZIP
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
项目:BaijiClient4Android
文件:HurlStack.java
private HttpEntity getEntityFromConnection(HttpURLConnection connection) {
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
inputStream = connection.getErrorStream();
}
entity.setContent(inputStream);
entity.setContentLength(connection.getContentLength());
entity.setContentEncoding(connection.getContentEncoding());
entity.setContentType(connection.getContentType());
return entity;
}
项目:trap
文件:POSTIntegrationTests.java
@Test
public void testLargePostChunked() throws Exception
{
byte[] testData = new byte[128*1024];
for (int i=0; i<testData.length; i++)
testData[i] = (byte) (i%255);
HttpPost post = new HttpPost("http://localhost:8192/");
ResponseHandler<byte[]> responseHandler = new BasicResponseHandler();
BasicHttpEntity entity = new BasicHttpEntity();
entity.setChunked(true);
entity.setContent(new ByteArrayInputStream(testData));
post.setEntity(entity);
byte[] responseBody = httpclient.execute(post, responseHandler);
Assert.assertArrayEquals(testData, responseBody);
}
项目:wso2-axis2
文件:AxisHttpResponseImpl.java
public void commit() throws IOException, HttpException {
if (this.commited) {
return;
}
this.commited = true;
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, this.conn);
this.context.setAttribute(ExecutionContext.HTTP_RESPONSE, this.response);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setChunked(true);
entity.setContentType(this.contentType);
this.response.setEntity(entity);
this.httpproc.process(this.response, this.context);
this.conn.sendResponse(this.response);
}
项目:spring-cloud-netflix
文件:RibbonApacheHttpResponseTests.java
@Test
public void testNotNullEntity() throws Exception {
StatusLine statusLine = mock(StatusLine.class);
given(statusLine.getStatusCode()).willReturn(204);
HttpResponse response = mock(HttpResponse.class);
given(response.getStatusLine()).willReturn(statusLine);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(new byte[0]));
given(response.getEntity()).willReturn(entity);
RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com"));
assertThat(httpResponse.isSuccess(), is(true));
assertThat(httpResponse.hasPayload(), is(true));
assertThat(httpResponse.getPayload(), is(notNullValue()));
assertThat(httpResponse.getInputStream(), is(notNullValue()));
}
项目:baseline
文件:TestJSONHandling.java
@Test
public void shouldReceiveErrorOnMakingPostWithInvalidJsonObject() throws ExecutionException, InterruptedException, JsonProcessingException {
// noinspection ConstantConditions
String serialized = mapper.writeValueAsString(new JsonObject(null, "allen")); // yes; I know I'm using 'null'
ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(contentInputStream);
HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
post.setEntity(entity);
Future<HttpResponse> future = client.getClient().execute(post, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_BAD_REQUEST));
}
项目:baseline
文件:TestJSONHandling.java
@Test
public void shouldSuccessfullyProcessJson() throws ExecutionException, InterruptedException, IOException {
JsonObject value = new JsonObject("unhappy", "allen");
String serialized = mapper.writeValueAsString(value);
ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(contentInputStream);
HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
post.setEntity(entity);
Future<HttpResponse> future = client.getClient().execute(post, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));
assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()), equalTo(getResponseValue(value)));
}
项目:barterli_android
文件:HurlStack.java
/**
* 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;
}
项目:fiware-rss
文件:ResponseHandlerTest.java
/**
*
*/
@Test
public void handleResponseTest() throws Exception {
ResponseHandler handler = new ResponseHandler();
HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse responseSent = factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK,
"reason"), null);
HttpResponse response = handler.handleResponse(responseSent);
Assert.assertEquals(handler.getStatus(), HttpStatus.SC_OK);
Assert.assertFalse(handler.hasContent());
// response with content.
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream = new ByteArrayInputStream("new content".getBytes());
entity.setContent(inputStream);
entity.setContentLength("new content".length()); // sets the length
response.setEntity(entity);
response = handler.handleResponse(responseSent);
Assert.assertEquals("new content", handler.getResponseContent());
}
项目:Repository-RI
文件:IntegrationTestHelper.java
public HttpResponse postResourceMeta(String collectionsId, String resource, List <Header> headers) throws IOException {
String finalURL = collectionServiceUrl + collectionsId;
HttpPost request = new HttpPost(finalURL);
//Add Headers
for (Header header : headers) {
request.setHeader(header);
}
//Add Entity
BasicHttpEntity entity = new BasicHttpEntity();
InputStream stream = new ByteArrayInputStream(resource.getBytes());
entity.setContent(stream);
request.setEntity(entity);
HttpResponse response = client.execute(request);
request.releaseConnection();
return response;
}
项目:Repository-RI
文件:IntegrationTestHelper.java
public HttpResponse putResourceMeta(String resourceId, String resource, List <Header> headers) throws IOException {
String finalURL = collectionServiceUrl + resourceId + ".meta";
HttpPut request = new HttpPut(finalURL);
//Add Headers
for (Header header : headers) {
request.setHeader(header);
}
//Add Entity
BasicHttpEntity entity = new BasicHttpEntity();
InputStream stream = new ByteArrayInputStream(resource.getBytes());
entity.setContent(stream);
request.setEntity(entity);
HttpResponse response = client.execute(request);
request.releaseConnection();
return response;
}
项目:Repository-RI
文件:IntegrationTestHelper.java
public HttpResponse putResourceContent(String resourceId, String resourceContent, List <Header> headers) throws IOException {
String finalURL = collectionServiceUrl + resourceId;
HttpPut request = new HttpPut(finalURL);
//Add Headers
for (Header header : headers) {
request.setHeader(header);
}
//Add Entity
BasicHttpEntity entity = new BasicHttpEntity();
InputStream stream = new ByteArrayInputStream(resourceContent.getBytes());
entity.setContent(stream);
request.setEntity(entity);
HttpResponse response = client.execute(request);
request.releaseConnection();
return response;
}
项目:Repository-RI
文件:IntegrationTestHelper.java
public HttpResponse postCollection(String collectionId, String collection, List <Header> headers) throws IOException {
String finalURL = collectionServiceUrl + collectionId;
HttpPost request = new HttpPost(finalURL);
//Add Headers
for (Header header : headers) {
request.setHeader(header);
}
//Add Entity
BasicHttpEntity entity = new BasicHttpEntity();
InputStream stream = new ByteArrayInputStream(collection.getBytes());
entity.setContent(stream);
request.setEntity(entity);
HttpResponse response = client.execute(request);
request.releaseConnection();
return response;
}
项目:Repository-RI
文件:IntegrationTestHelper.java
public HttpResponse postQuery(String query, List <Header> headers) throws IOException {
String finalURL = queryServiceUrl;
HttpPost request = new HttpPost(finalURL);
//Add Headers
for (Header header : headers) {
request.setHeader(header);
}
BasicHttpEntity entity = new BasicHttpEntity();
InputStream stream = new ByteArrayInputStream(query.getBytes());
entity.setContent(stream);
request.setEntity(entity);
HttpResponse response = client.execute(request);
request.releaseConnection();
return response;
}
项目:ZombieLink
文件:RequestParamEndpointTest.java
/**
* <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
*
* @since 1.3.0
*/
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
String subpath = "/bufferedhttpentity";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
BasicHttpEntity bhe = new BasicHttpEntity();
bhe.setContent(parallelInputStream);
stubFor(put(urlEqualTo(subpath))
.willReturn(aResponse()
.withStatus(200)));
requestEndpoint.bufferedHttpEntity(inputStream);
verify(putRequestedFor(urlEqualTo(subpath))
.withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
项目:laposte-android
文件:ExtHttpClientStack.java
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;
}
项目:RoboZombie
文件:RequestParamEndpointTest.java
/**
* <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
*
* @since 1.3.0
*/
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
String subpath = "/bufferedhttpentity";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
BasicHttpEntity bhe = new BasicHttpEntity();
bhe.setContent(parallelInputStream);
stubFor(put(urlEqualTo(subpath))
.willReturn(aResponse()
.withStatus(200)));
requestEndpoint.bufferedHttpEntity(inputStream);
verify(putRequestedFor(urlEqualTo(subpath))
.withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
项目:fcrepo4
文件:LdpTestSuiteIT.java
@Test
public void runLDPBasicContainerTestSuite() throws IOException {
final String pid = "ldp-test-basic-" + UUID.randomUUID().toString();
final HttpPut request = new HttpPut(serverAddress + pid);
final BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(IOUtils.toInputStream("<> a <" + BASIC_CONTAINER + "> ."));
request.setEntity(entity);
request.setHeader(CONTENT_TYPE, "text/turtle");
try (final CloseableHttpResponse response = executeWithBasicAuth(request)) {
assertEquals(CREATED.getStatusCode(), response.getStatusLine().getStatusCode());
final HashMap<String, String> options = new HashMap<>();
options.put("server", serverAddress + pid);
options.put("output", "report-basic");
options.put("basic", "true");
options.put("non-rdf", "true");
options.put("read-only-prop", "http://fedora.info/definitions/v4/repository#uuid");
final LdpTestSuite testSuite = new LdpTestSuite(options);
testSuite.run();
assertTrue("The LDP test suite is only informational", true);
}
}
项目:fcrepo4
文件:LdpTestSuiteIT.java
@Test
public void runLDPDirectContainerTestSuite() throws IOException {
final String pid = "ldp-test-direct-" + UUID.randomUUID().toString();
final HttpPut request = new HttpPut(serverAddress + pid);
final BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(IOUtils.toInputStream("<> a <" + DIRECT_CONTAINER + "> ;" +
" <" + LDP_NAMESPACE + "membershipResource> <> ;" +
" <" + LDP_NAMESPACE + "hasMemberRelation> <" + LDP_NAMESPACE + "member> ."));
request.setEntity(entity);
request.setHeader(CONTENT_TYPE, "text/turtle");
try (final CloseableHttpResponse response = executeWithBasicAuth(request)) {
assertEquals(CREATED.getStatusCode(), response.getStatusLine().getStatusCode());
final HashMap<String, String> options = new HashMap<>();
options.put("server", serverAddress + pid);
options.put("output", "report-direct");
options.put("direct", "true");
options.put("non-rdf", "true");
options.put("read-only-prop", "http://fedora.info/definitions/v4/repository#uuid");
final LdpTestSuite testSuite = new LdpTestSuite(options);
testSuite.run();
assertTrue("The LDP test suite is only informational", true);
}
}
项目:fcrepo4
文件:LdpTestSuiteIT.java
@Test
public void runLDPIndirectContainerTestSuite() throws IOException {
final String pid = "ldp-test-indirect-" + UUID.randomUUID().toString();
final HttpPut request = new HttpPut(serverAddress + pid);
final BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(IOUtils.toInputStream("<> a <" + INDIRECT_CONTAINER + ">;" +
" <" + LDP_NAMESPACE + "membershipResource> <> ;" +
" <" + LDP_NAMESPACE + "insertedContentRelation> <" + LDP_NAMESPACE + "MemberSubject> ;" +
" <" + LDP_NAMESPACE + "hasMemberRelation> <" + LDP_NAMESPACE + "member> ."));
request.setEntity(entity);
request.setHeader(CONTENT_TYPE, "text/turtle");
try (final CloseableHttpResponse response = executeWithBasicAuth(request)) {
assertEquals(CREATED.getStatusCode(), response.getStatusLine().getStatusCode());
final HashMap<String, String> options = new HashMap<>();
options.put("server", serverAddress + pid);
options.put("output", "report-indirect");
options.put("indirect", "true");
options.put("non-rdf", "true");
options.put("read-only-prop", "http://fedora.info/definitions/v4/repository#uuid");
final LdpTestSuite testSuite = new LdpTestSuite(options);
testSuite.run();
assertTrue("The LDP test suite is only informational", true);
}
}
项目:ezScrum
文件:StoryWebServiceControllerTest.java
@Test
public void testAddExistedTask() throws Exception {
// create 3 tasks in project
TaskObject task1 = new TaskObject(mProject.getId());
task1.setName("TASK_NAME1").save();
TaskObject task2 = new TaskObject(mProject.getId());
task2.setName("TASK_NAME2").save();
TaskObject task3 = new TaskObject(mProject.getId());
task3.setName("TASK_NAME3").save();
// initial request data,add task#1 & #3 to story#1
StoryObject story = mASTS.getStories().get(0);
String taskIdJsonString = String.format("[%s, %s]", task1.getId(), task2.getId());
String URL = String.format(API_URL, mProjectName, story.getId() + "/add-existed-task", mUsername, mPassword);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(taskIdJsonString.getBytes()));
entity.setContentEncoding("utf-8");
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(entity);
mHttpClient.execute(httpPost);
story.reload();
assertEquals(2, story.getTasks().size());
}
项目:android_volley_examples
文件:ExtHttpClientStack.java
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;
}