Java Code Examples for org.apache.http.HttpResponse#setEntity()

The following examples show how to use org.apache.http.HttpResponse#setEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConanClient.java    From nexus-repository-conan with Eclipse Public License 1.0 7 votes vote down vote up
public HttpResponse getHttpResponse(final String path) throws IOException {
  try (CloseableHttpResponse closeableHttpResponse = super.get(path)) {
    HttpEntity entity = closeableHttpResponse.getEntity();

    BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
    String content = EntityUtils.toString(entity);
    basicHttpEntity.setContent(IOUtils.toInputStream(content));

    basicHttpEntity.setContentEncoding(entity.getContentEncoding());
    basicHttpEntity.setContentLength(entity.getContentLength());
    basicHttpEntity.setContentType(entity.getContentType());
    basicHttpEntity.setChunked(entity.isChunked());

    StatusLine statusLine = closeableHttpResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(basicHttpEntity);
    response.setHeaders(closeableHttpResponse.getAllHeaders());
    response.setLocale(closeableHttpResponse.getLocale());
    return response;
  }
}
 
Example 2
Source File: RemoteResponse.java    From logbook with MIT License 6 votes vote down vote up
@Override
public State buffer(final HttpResponse response) throws IOException {
    @Nullable final HttpEntity entity = response.getEntity();

    if (entity == null) {
        return new Passing();
    } else {
        final byte[] body = toByteArray(entity);

        final ByteArrayEntity copy = new ByteArrayEntity(body);
        copy.setChunked(entity.isChunked());
        copy.setContentEncoding(entity.getContentEncoding());
        copy.setContentType(entity.getContentType());

        response.setEntity(copy);

        return new Buffering(body);
    }
}
 
Example 3
Source File: CachedHttpResponseGenerator.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * If I was able to use a {@link CacheEntry} to response to the
 * {@link org.apache.http.HttpRequest} then generate an {@link HttpResponse}
 * based on the cache entry.
 * 
 * @param entry
 *            {@link CacheEntry} to transform into an {@link HttpResponse}
 * @return {@link HttpResponse} that was constructed
 */
HttpResponse generateResponse(HttpCacheEntry entry) {

	Date now = new Date();
	HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
			entry.getStatusCode(), entry.getReasonPhrase());

	HttpEntity entity = new CacheEntity(entry);
	response.setHeaders(entry.getAllHeaders());
	addMissingContentLengthHeader(response, entity);
	response.setEntity(entity);

	long age = this.validityStrategy.getCurrentAgeSecs(entry, now);
	if (age > 0) {
		if (age >= Integer.MAX_VALUE) {
			response.setHeader(HeaderConstants.AGE, "2147483648");
		} else {
			response.setHeader(HeaderConstants.AGE, "" + ((int) age));
		}
	}

	return response;
}
 
Example 4
Source File: AllureHttpClientResponse.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final HttpResponse response,
                    final HttpContext context) throws IOException {

    final HttpResponseAttachment.Builder builder = create("Response")
            .setResponseCode(response.getStatusLine().getStatusCode());

    Stream.of(response.getAllHeaders())
            .forEach(header -> builder.setHeader(header.getName(), header.getValue()));

    if (response.getEntity() != null) {
        final LoggableEntity loggableEntity = new LoggableEntity(response.getEntity());
        response.setEntity(loggableEntity);

        builder.setBody(loggableEntity.getBody());
    } else {
        builder.setBody("No body present");
    }

    final HttpResponseAttachment responseAttachment = builder.build();
    processor.addAttachment(responseAttachment, renderer);
}
 
Example 5
Source File: HTTPSession.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Header ceheader = entity.getContentEncoding();
    if (ceheader != null) {
      HeaderElement[] codecs = ceheader.getElements();
      for (HeaderElement h : codecs) {
        if (h.getName().equalsIgnoreCase("deflate")) {
          response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
          return;
        }
      }
    }
  }
}
 
Example 6
Source File: MockHttpClient.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) {
    requestExecuted = request;
    StatusLine statusLine = new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), mStatusCode, "");
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(mResponseEntity);

    return response;
}
 
Example 7
Source File: TestHttpCallTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    super.handle(request, response, context);

    if (!isValidRequest(request)) {
        response.setStatusCode(405);
        response.setEntity(null);
    }
}
 
Example 8
Source File: MixerHttpClientTest.java    From beam-client-java with MIT License 5 votes vote down vote up
private HttpResponse prepareResponse(int expectedResponseStatus, String expectedResponseBody) {
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), expectedResponseStatus, ""));
    response.setStatusCode(expectedResponseStatus);
    try {
        response.setEntity(new StringEntity(expectedResponseBody));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
    return response;
}
 
Example 9
Source File: AuthHandler.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) {
    String creds = (String) context.getAttribute("creds");
    if (creds == null || !creds.equals(getExpectedCredentials())) {
        response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
    } else {
        response.setEntity(new ByteArrayEntity(responseBody));
    }
}
 
Example 10
Source File: ApiServer.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void writeResponse(final HttpResponse resp, final String responseText, final int statusCode, final String responseType, final String reasonPhrase) {
    try {
        resp.setStatusCode(statusCode);
        resp.setReasonPhrase(reasonPhrase);

        final BasicHttpEntity body = new BasicHttpEntity();
        if (HttpUtils.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
            // JSON response
            body.setContentType(getJSONContentType());
            if (responseText == null) {
                body.setContent(new ByteArrayInputStream("{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes(HttpUtils.UTF_8)));
            }
        } else {
            body.setContentType("text/xml");
            if (responseText == null) {
                body.setContent(new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes(HttpUtils.UTF_8)));
            }
        }

        if (responseText != null) {
            body.setContent(new ByteArrayInputStream(responseText.getBytes(HttpUtils.UTF_8)));
        }
        resp.setEntity(body);
    } catch (final Exception ex) {
        s_logger.error("error!", ex);
    }
}
 
Example 11
Source File: AopHttpClient.java    From ArgusAPM with Apache License 2.0 5 votes vote down vote up
private static HttpResponse handleResponse(HttpResponse response, NetInfo data) {
    data.setStatusCode(response.getStatusLine().getStatusCode());
    Header[] headers = response.getHeaders("Content-Length");
    if ((headers != null) && (headers.length > 0)) {
        try {
            long l = Long.parseLong(headers[0].getValue());
            data.setReceivedBytes(l);
            if (DEBUG) {
                LogX.d(TAG, SUB_TAG, "-handleResponse--end--1");
            }
            data.end();
        } catch (NumberFormatException e) {
            if (Env.DEBUG) {
                LogX.d(TAG, SUB_TAG, "NumberFormatException ex : " + e.getMessage());
            }
        }
    } else if (response.getEntity() != null) {
        response.setEntity(new AopHttpResponseEntity(response.getEntity(), data));
    } else {
        data.setReceivedBytes(0);
        if (DEBUG) {
            LogX.d(TAG, SUB_TAG, "----handleResponse--end--2");
        }
        data.end();
    }
    if (DEBUG) {
        LogX.d(TAG, SUB_TAG, "execute:" + data.toString());
    }
    return response;
}
 
Example 12
Source File: ClusterServiceServletHttpHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void writeResponse(final HttpResponse response, final int statusCode, String content) {
    if (content == null) {
        content = "";
    }
    response.setStatusCode(statusCode);
    final BasicHttpEntity body = new BasicHttpEntity();
    body.setContentType("text/html; charset=UTF-8");

    final byte[] bodyData = content.getBytes();
    body.setContent(new ByteArrayInputStream(bodyData));
    body.setContentLength(bodyData.length);
    response.setEntity(body);
}
 
Example 13
Source File: HttpProjectConfigManagerTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testGetDatafileHttpResponse2XX() throws Exception {
    String modifiedStamp = "Wed, 24 Apr 2019 07:07:07 GMT";
    HttpResponse getResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
    getResponse.setEntity(new StringEntity(datafileString));
    getResponse.setHeader(HttpHeaders.LAST_MODIFIED, modifiedStamp);

    String datafile = projectConfigManager.getDatafileFromResponse(getResponse);
    assertNotNull(datafile);

    assertEquals("4", parseProjectConfig(datafile).getVersion());
    // Confirm last modified time is set
    assertEquals(modifiedStamp, projectConfigManager.getLastModified());
}
 
Example 14
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected void handleMetadataRequest(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    response.setStatusCode(200);
    response.setHeader("Cache-Control", "public, max-age=31536000");
    response.setHeader("Content-Type", "application/xml");
    response.setEntity(new StringEntity(createMetadata()));
}
 
Example 15
Source File: HttpUtilsTest.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Test sending a message, expecting a successful response.
 */
@Test
public void sendMessageSuccessTest() {

	try {
		String endpoint = "https://some-test-endpoint";
		boolean onlyAllowHttps = true;

		String xml = "<element>test response xml</element>";

		// Dummy and Mock required objects
		ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 1);
		int statusCode = 200;
		String statusReason = "";
		HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(protocolVersion, statusCode, statusReason));
		httpResponse.setEntity(new StringEntity(xml));

		HttpConfiguration httpConfigurationMock = mock(HttpConfiguration.class);
		when(httpConfigurationMock.getEndpoint()).thenReturn(endpoint);
		when(httpConfigurationMock.isOnlyAllowHttps()).thenReturn(onlyAllowHttps);

		HttpClient httpClientMock = mock(HttpClient.class);
		when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponse);

		// Execute the method
		String response = HttpUtils.sendMessage(xml, httpClientMock, httpConfigurationMock);

		// Check the repsonse
		Assert.assertEquals(response, xml);
	} catch (Exception e) {
		Assert.fail("Unexpected exception: " + e.getMessage());
	}
}
 
Example 16
Source File: LocalWebServerHttpRequestHandler.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void handleRequest(HttpRequest request, HttpResponse response, boolean head) throws HttpException,
		IOException, CoreException, URISyntaxException
{
	String target = URLDecoder.decode(request.getRequestLine().getUri(), IOUtil.UTF_8);
	URI uri = URIUtil.fromString(target);
	IFileStore fileStore = uriMapper.resolve(uri);
	IFileInfo fileInfo = fileStore.fetchInfo();
	if (fileInfo.isDirectory())
	{
		fileInfo = getIndex(fileStore);
		if (fileInfo.exists())
		{
			fileStore = fileStore.getChild(fileInfo.getName());
		}
	}
	if (!fileInfo.exists())
	{
		response.setStatusCode(HttpStatus.SC_NOT_FOUND);
		response.setEntity(createTextEntity(MessageFormat.format(
				Messages.LocalWebServerHttpRequestHandler_FILE_NOT_FOUND, uri.getPath())));
	}
	else if (fileInfo.isDirectory())
	{
		response.setStatusCode(HttpStatus.SC_FORBIDDEN);
		response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_FORBIDDEN));
	}
	else
	{
		response.setStatusCode(HttpStatus.SC_OK);
		if (head)
		{
			response.setEntity(null);
		}
		else
		{
			File file = fileStore.toLocalFile(EFS.NONE, new NullProgressMonitor());
			final File temporaryFile = (file == null) ? fileStore.toLocalFile(EFS.CACHE, new NullProgressMonitor())
					: null;
			response.setEntity(new NFileEntity((file != null) ? file : temporaryFile, getMimeType(fileStore
					.getName()))
			{
				@Override
				public void close() throws IOException
				{
					try
					{
						super.close();
					}
					finally
					{
						if (temporaryFile != null && !temporaryFile.delete())
						{
							temporaryFile.deleteOnExit();
						}
					}
				}
			});
		}
	}
}
 
Example 17
Source File: DapTestCommon.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpResponse execute(HttpRequestBase rq) throws IOException {
  URI uri = rq.getURI();
  DapController controller = getController(uri);
  StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller);
  mvcbuilder.setValidator(new TestServlet.NullValidator());
  MockMvc mockMvc = mvcbuilder.build();
  MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri);
  // We need to use only the path part
  mockrb.servletPath(uri.getPath());
  // Move any headers from rq to mockrb
  Header[] headers = rq.getAllHeaders();
  for (int i = 0; i < headers.length; i++) {
    Header h = headers[i];
    mockrb.header(h.getName(), h.getValue());
  }
  // Since the url has the query parameters,
  // they will automatically be parsed and added
  // to the rb parameters.

  // Finally set the resource dir
  mockrb.requestAttr("RESOURCEDIR", this.resourcepath);

  // Now invoke the servlet
  MvcResult result;
  try {
    result = mockMvc.perform(mockrb).andReturn();
  } catch (Exception e) {
    throw new IOException(e);
  }

  // Collect the output
  MockHttpServletResponse res = result.getResponse();
  byte[] byteresult = res.getContentAsByteArray();

  // Convert to HttpResponse
  HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), "");
  if (response == null)
    throw new IOException("HTTPMethod.executeMock: Response was null");
  Collection<String> keys = res.getHeaderNames();
  // Move headers to the response
  for (String key : keys) {
    List<String> values = res.getHeaders(key);
    for (String v : values) {
      response.addHeader(key, v);
    }
  }
  ByteArrayEntity entity = new ByteArrayEntity(byteresult);
  String sct = res.getContentType();
  entity.setContentType(sct);
  response.setEntity(entity);
  return response;
}
 
Example 18
Source File: HeaderManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Copies end-to-end headers from a response received from the server to the response to be sent to the client.
 * 
 * @param outgoingRequest
 *            the request sent
 * @param incomingRequest
 *            the original request received from the client
 * @param httpClientResponse
 *            the response received from the provider application
 * @return the response to be sent to the client
 */
public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest,
        HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) {
    HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine());
    result.setEntity(httpClientResponse.getEntity());
    String originalUri = incomingRequest.getRequestLine().getUri();
    String baseUrl = outgoingRequest.getBaseUrl().toString();
    String visibleBaseUrl = outgoingRequest.getOriginalRequest().getVisibleBaseUrl();
    for (Header header : httpClientResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        try {
            // Ignore Content-Encoding and Content-Type as these headers are
            // set in HttpEntity
            if (!HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name)) {
                if (isForwardedResponseHeader(name)) {
                    // Some headers containing an URI have to be rewritten
                    if (HttpHeaders.LOCATION.equalsIgnoreCase(name)
                            || HttpHeaders.CONTENT_LOCATION.equalsIgnoreCase(name)) {
                        // Header contains only an url
                        value = urlRewriter.rewriteUrl(value, originalUri, baseUrl, visibleBaseUrl, true);
                        value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        result.addHeader(name, value);
                    } else if ("Link".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Link: </feed>; rel="alternate"

                        if (value.startsWith("<") && value.contains(">")) {
                            String urlValue = value.substring(1, value.indexOf(">"));

                            String targetUrlValue =
                                    urlRewriter.rewriteUrl(urlValue, originalUri, baseUrl, visibleBaseUrl, true);
                            targetUrlValue = HttpResponseUtils.removeSessionId(targetUrlValue, httpClientResponse);

                            value = value.replace("<" + urlValue + ">", "<" + targetUrlValue + ">");
                        }

                        result.addHeader(name, value);

                    } else if ("Refresh".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Refresh: 5; url=http://www.example.com
                        int urlPosition = value.indexOf("url=");
                        if (urlPosition >= 0) {
                            value = urlRewriter.rewriteRefresh(value, originalUri, baseUrl, visibleBaseUrl);
                            value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        }
                        result.addHeader(name, value);
                    } else if ("P3p".equalsIgnoreCase(name)) {
                        // Do not translate url yet.
                        // P3P is used with a default fixed url most of the
                        // time.
                        result.addHeader(name, value);
                    } else {
                        result.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception e1) {
            // It's important not to fail here.
            // An application can always send corrupted headers, and we
            // should not crash
            LOG.error("Error while copying headers", e1);
            result.addHeader("X-Esigate-Error", "Error processing header " + name + ": " + value);
        }
    }
    return BasicCloseableHttpResponse.adapt(result);
}
 
Example 19
Source File: MixerHttpClientTest.java    From beam-client-java with MIT License 4 votes vote down vote up
@Test
public void itHandlesCSRF() {
    mixerAPI = new MixerAPI("clientId");
    defaultHttpClient = mock(HttpClient.class);

    // This is done because Mockito is not able to mock methods that are called within the class'
    // Constructor.
    class MockableMixerHttpClient extends MixerHttpClient {
        private MockableMixerHttpClient(MixerAPI mixer) {
            super(mixer, "clientId");
        }

        @Override
        protected HttpClient buildHttpClient() {
            return defaultHttpClient;
        }
    }
    mixerHttpClient = new MockableMixerHttpClient(mixerAPI);


    HttpResponse csrfResponse = prepareResponse(461, "{\"error\":\"Invalid or missing CSRF header, see details here: <https://dev.mixer.pro/rest.html#csrf>\",\"statusCode\":461}");
    csrfResponse.addHeader(new BasicHeader(CSRF_TOKEN_HEADER, "abc123"));
    csrfResponse.setEntity(mock(HttpEntity.class));

    HttpResponse okResponse = prepareResponse(200, "{\"id\":314,\"userId\":344,\"token\":\"Mixer\",\"online\":false,\"featured\":false,\"partnered\":false,\"transcodingProfileId\":1,\"suspended\":false,\"name\":\"Weekly Updates and more!\"}");
    okResponse.addHeader(new BasicHeader(CSRF_TOKEN_HEADER, "abc123"));

    try {
        doReturn(csrfResponse)
                .doReturn(okResponse)
                .when(defaultHttpClient)
                .execute(any(HttpUriRequest.class), isNull(HttpContext.class));
    } catch (IOException e) {
        Assert.fail();
    }

    Futures.addCallback(mixerHttpClient.get("/channels/314", MixerUser.class, null), new FutureCallback<MixerUser>() {
        @Override
        public void onSuccess(MixerUser mixerUser) {
            Assert.assertEquals(mixerHttpClient.getCsrfToken(), "abc123");
        }

        @Override
        public void onFailure(Throwable throwable) {
            Assert.fail();
        }
    });
}
 
Example 20
Source File: RequestWsInfoHandler.java    From screen-share-to-browser with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    StringEntity stringEntity = new StringEntity("" + MainViewModel.localIpText.get() + ":" + MainViewModel.wsServerPort.get(), "utf-8");
    response.setEntity(stringEntity);
}