Java Code Examples for org.apache.http.httpresponse#setHeader()
The following examples show how to use
org.apache.http.httpresponse#setHeader() .
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: RemoteBounceProxyFacadeTest.java From joynr with Apache License 2.0 | 6 votes |
/** * Sets the HTTP response returned by the * {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} * method. * * @param httpStatus * the desired HTTP status to be returned as HTTP response * @throws HttpException * @throws IOException */ private void setMockedHttpRequestHandlerResponse(final int httpStatus, final String location, final String bpId) throws HttpException, IOException { // HttpResponse is set as out parameter of the handle method. The way to // set out parameters with Mockito is to use doAnswer Answer<Void> answerForHttpResponse = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { HttpResponse httpResponse = (HttpResponse) invocation.getArguments()[1]; httpResponse.setStatusCode(httpStatus); httpResponse.setHeader("Location", location); httpResponse.setHeader("bp", bpId); return null; } }; Mockito.doAnswer(answerForHttpResponse).when(handler).handle(any(HttpRequest.class), any(HttpResponse.class), any(HttpContext.class)); }
Example 2
Source File: TestWebServer.java From curly with Apache License 2.0 | 6 votes |
void handleHttpRequest(HttpRequest request, HttpResponse response, HttpContext context) throws UnsupportedEncodingException { lastRequest = request; try { if (requireLogin && request.getFirstHeader("Authorization") == null) { response.setStatusCode(401); response.setHeader("WWW-Authenticate", "Basic realm=\"test\""); } else { Thread.sleep(processingDelay); if (request.getRequestLine().getUri().contains("failure")) { response.setStatusCode(403); } else { response.setEntity(new StringEntity(responseMessage)); } } } catch (InterruptedException ex) { Logger.getLogger(TestWebServer.class.getName()).log(Level.SEVERE, null, ex); } }
Example 3
Source File: VolleyRequestPipeline.java From jus with Apache License 2.0 | 6 votes |
@Override public RequestPipeline prepare(States.GenericState state) { NetworkResponse resp = Util.newResponse(state); HttpResponse vResp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), resp.statusCode, "OK"); vResp.setEntity(new ByteArrayEntity(resp.data)); for(String h:resp.headers.names()) { vResp.setHeader(h,resp.headers.get(h)); } MockVolleyHttpStack stack = new MockVolleyHttpStack(); stack.setResponseToReturn(vResp); this.requestQueue = new com.android.volley.RequestQueue( new VolleyNoCache(), new BasicNetwork(stack), state.concurrencyLevel ); requestQueue.start(); return this; }
Example 4
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
public void testCacheAndLoadBalancing() throws Exception { properties = new PropertiesBuilder().on(properties) .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080, http://127.0.0.1:8080") .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.PRESERVE_HOST, true).build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("0"); response.setHeader("Cache-control", "public, max-age=3600"); mockConnectionManager.setResponse(response); HttpResponse result = executeRequest(); assertTrue("Response content should be '0'", compare(response, result)); // Second request should reuse the cache entry even if it uses a // different node HttpResponse response1 = createMockResponse("1"); mockConnectionManager.setResponse(response1); result = executeRequest(); assertTrue("Response content should be unchanged as cache should be used.", compare(response, result)); }
Example 5
Source File: CachedHttpResponseGenerator.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
public void testXCacheHeader() throws Exception { properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.X_CACHE_HEADER, true).build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("0"); response.setHeader("Cache-control", "public, max-age=3600"); mockConnectionManager.setResponse(response); HttpResponse result = executeRequest(); assertNotNull("X-Cache header is missing", result.getFirstHeader("X-Cache")); assertTrue("X-Cache header should start with MISS", result.getFirstHeader("X-Cache").getValue().startsWith("MISS")); result = executeRequest(); assertNotNull("X-Cache header is missing", result.getFirstHeader("X-Cache")); assertTrue("X-Cache header should start with HIT", result.getFirstHeader("X-Cache").getValue() .startsWith("HIT")); result = executeRequest(); assertNotNull("X-Cache header is missing", result.getFirstHeader("X-Cache")); assertTrue("There should be only 1 header X-Cache", result.getHeaders("X-Cache").length == 1); assertTrue("X-Cache header should start with HIT", result.getFirstHeader("X-Cache").getValue() .startsWith("HIT")); }
Example 7
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
public void testCacheTtl() throws Exception { properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.TTL, 1).build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("0"); response.setHeader("Cache-control", "no-cache"); mockConnectionManager.setResponse(response); HttpResponse result = executeRequest(); assertTrue("Response content should be '0'", compare(response, result)); // Second request should use cache HttpResponse response1 = createMockResponse("1"); response.setHeader("Cache-control", "no-cache"); mockConnectionManager.setResponse(response1); result = executeRequest(); assertTrue("Response content should be unchanged as cache should be used.", compare(response, result)); // Third request after cache has expired Thread.sleep(ONE_SECOND); result = executeRequest(); assertTrue("Response should have been refreshed.", compare(response1, result)); }
Example 8
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
public void testEhCache() throws Exception { properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.CACHE_STORAGE, EhcacheCacheStorage.class) // Default .build(); // value createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("0"); response.setHeader("Cache-control", "public, max-age=3600"); mockConnectionManager.setResponse(response); HttpResponse result = executeRequest(); assertTrue("Response content should be '0'", compare(response, result)); // Second request should reuse the cache entry even if it uses a // different node HttpResponse response1 = createMockResponse("1"); mockConnectionManager.setResponse(response1); result = executeRequest(); assertTrue("Response content should be unchanged as cache should be used on error.", compare(response, result)); }
Example 9
Source File: BasicHttpCache.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
HttpResponse generateIncompleteResponseError(HttpResponse response, Resource resource) { int contentLength = Integer.parseInt(response.getFirstHeader( "Content-Length").getValue()); HttpResponse error = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_GATEWAY, "Bad Gateway"); error.setHeader("Content-Type", "text/plain;charset=UTF-8"); String msg = String.format("Received incomplete response " + "with Content-Length %d but actual body length %d", contentLength, resource.length()); byte[] msgBytes = msg.getBytes(); error.setHeader("Content-Length", Integer.toString(msgBytes.length)); error.setEntity(new ByteArrayEntity(msgBytes)); return error; }
Example 10
Source File: MockIpdServer.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(200); response.setHeader("Cache-Control", "public, max-age=31536000"); response.setEntity(new StringEntity("{\"jwks_uri\": \"" + uri + CTX_KEYS + "\",\n" + "\"issuer\": \"" + uri + "\", \"unknownPropertyToBeIgnored\": 42}")); }
Example 11
Source File: CachedHttpResponseGenerator.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
private void addMissingContentLengthHeader(HttpResponse response, HttpEntity entity) { if (transferEncodingIsPresent(response)) return; Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN); if (contentLength == null) { contentLength = new BasicHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); response.setHeader(contentLength); } }
Example 12
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 5 votes |
public void test304CachedResponseIsReusedWithIfModifiedSinceRequest() throws Exception { properties = new PropertiesBuilder() // .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.X_CACHE_HEADER, true) // .build(); createHttpClientRequestExecutor(); // First request String now = DateUtils.formatDate(new Date()); String yesterday = DateUtils.formatDate(new Date(System.currentTimeMillis() - ONE_DAY)); String inOneHour = DateUtils.formatDate(new Date(System.currentTimeMillis() + ONE_HOUR)); HttpResponse response = createMockResponse(HttpStatus.SC_NOT_MODIFIED, null); response.setHeader("Date", now); response.setHeader("Expires", inOneHour); response.setHeader("Cache-Control", "max-age=3600"); mockConnectionManager.setResponse(response); // First request to load the cache DriverRequest httpRequest = TestUtils.createDriverRequest(driver); httpRequest.getOriginalRequest().addHeader("If-Modified-Since", yesterday); OutgoingRequest apacheHttpRequest = httpClientRequestExecutor.createOutgoingRequest(httpRequest, "http://localhost:8080", true); apacheHttpRequest.addHeader("If-Modified-Since", yesterday); HttpResponse result = httpClientRequestExecutor.execute(apacheHttpRequest); assertTrue(result.getFirstHeader("X-cache").getValue().startsWith("MISS")); assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); // Second request should use cache DriverRequest httpRequest2 = TestUtils.createDriverRequest(driver); httpRequest2.getOriginalRequest().addHeader("If-Modified-Since", yesterday); OutgoingRequest apacheHttpRequest2 = httpClientRequestExecutor.createOutgoingRequest(httpRequest2, "http://localhost:8080", true); apacheHttpRequest2.addHeader("If-Modified-Since", yesterday); HttpResponse result2 = httpClientRequestExecutor.execute(apacheHttpRequest2); assertTrue(result2.getFirstHeader("X-cache").getValue().startsWith("HIT")); assertEquals(HttpStatus.SC_NOT_MODIFIED, result2.getStatusLine().getStatusCode()); }
Example 13
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 5 votes |
public void testXCacheHeaderWithLoadBalancing() throws Exception { // Use load balancing in round robin mode and check that the header // indicates properly the host that was used for the request properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.PRESERVE_HOST, true) // .set(Parameters.X_CACHE_HEADER, true) // .set(Parameters.REMOTE_URL_BASE_STRATEGY, Parameters.ROUNDROBIN) // .build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("1"); response.setHeader("Cache-control", "max-age=60"); mockConnectionManager.setResponse(response); DriverRequest httpRequest = TestUtils.createDriverRequest("http://localhost:8080", driver); OutgoingRequest apacheHttpRequest = httpClientRequestExecutor.createOutgoingRequest(httpRequest, "http://localhost:8080", true); HttpResponse result = httpClientRequestExecutor.execute(apacheHttpRequest); Header xCacheHeader1 = result.getFirstHeader("X-Cache"); assertNotNull("X-Cache header is missing", xCacheHeader1); response = createMockResponse("2"); response.setHeader("Cache-control", "max-age=60"); mockConnectionManager.setResponse(response); httpRequest = TestUtils.createDriverRequest("http://localhost:8080", driver); apacheHttpRequest = httpClientRequestExecutor.createOutgoingRequest(httpRequest, "http://127.0.0.1:8080", true); result = httpClientRequestExecutor.execute(apacheHttpRequest); Header xCacheHeader2 = result.getFirstHeader("X-Cache"); assertNotNull("X-Cache header is missing", xCacheHeader2); assertTrue("X-Cache header should indicate the first backend used", xCacheHeader1.getValue().startsWith("MISS from localhost")); assertTrue("X-Cache header should indicate reuse of the cache entry", xCacheHeader2.getValue().startsWith("HIT from 127.0.0.1")); }
Example 14
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 5 votes |
public void testXCacheHeaderWithLoadBalancingNoCache() throws Exception { // Use load balancing in round robin mode and check that the header // indicates properly the host that was used for the request properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.X_CACHE_HEADER, true) // .set(Parameters.REMOTE_URL_BASE_STRATEGY, Parameters.ROUNDROBIN) // .build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("1"); response.setHeader("Cache-control", "no-cache"); mockConnectionManager.setResponse(response); DriverRequest httpRequest = TestUtils.createDriverRequest("http://localhost:8080", driver); OutgoingRequest apacheHttpRequest = httpClientRequestExecutor.createOutgoingRequest(httpRequest, "http://localhost:8080", true); HttpResponse result = httpClientRequestExecutor.execute(apacheHttpRequest); Header xCacheHeader1 = result.getFirstHeader("X-Cache"); assertNotNull("X-Cache header is missing", xCacheHeader1); response = createMockResponse("2"); response.setHeader("Cache-control", "no-cache"); mockConnectionManager.setResponse(response); httpRequest = TestUtils.createDriverRequest("http://localhost:8080", driver); apacheHttpRequest = httpClientRequestExecutor.createOutgoingRequest(httpRequest, "http://127.0.0.1:8080", true); result = httpClientRequestExecutor.execute(apacheHttpRequest); Header xCacheHeader2 = result.getFirstHeader("X-Cache"); assertNotNull("X-Cache header is missing", xCacheHeader2); assertTrue("X-Cache header should indicate the first backend used", xCacheHeader1.getValue().startsWith("MISS from localhost")); assertTrue("X-Cache header should indicate the second backend used", xCacheHeader2.getValue().startsWith("MISS from 127.0.0.1")); assertFalse("The 2 nodes should have been used", xCacheHeader1.getValue().equals(xCacheHeader2.getValue())); }
Example 15
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 5 votes |
public void testCacheStaleIfError() throws Exception { properties = new PropertiesBuilder().on(properties) // .set(Parameters.USE_CACHE, true) // Default value .set(Parameters.STALE_IF_ERROR, 60) // .set(Parameters.STALE_WHILE_REVALIDATE, 60) // .set(Parameters.MIN_ASYNCHRONOUS_WORKERS, 1) // .set(Parameters.MAX_ASYNCHRONOUS_WORKERS, 10)// .set(Parameters.HEURISTIC_CACHING_ENABLED, false).build(); createHttpClientRequestExecutor(); // First request HttpResponse response = createMockResponse("0"); // HttpClient should store in cache and send a conditional request next time response.setHeader("Last-modified", "Fri, 20 May 2011 00:00:00 GMT"); response.setHeader("Cache-control", "max-age=0"); mockConnectionManager.setResponse(response); HttpResponse result = executeRequest(); assertTrue("Response content should be '0'", compare(response, result)); // Second request should use cache even if first response was a 404 HttpResponse response1 = createMockResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "1"); mockConnectionManager.setResponse(response1); result = executeRequest(); assertTrue("Response content should be unchanged as cache should be used on error.", compare(response, result)); Thread.sleep(ONE_HUNDRED_MS); // Third request no more error but stale-while-refresh should trigger a // background revalidation and serve the old version. HttpResponse response2 = createMockResponse(HttpStatus.SC_OK, "2"); mockConnectionManager.setResponse(response2); result = executeRequest(); assertTrue("Response should not have been refreshed yet.", compare(response, result)); // Wait until revalidation is complete Thread.sleep(ONE_HUNDRED_MS); // Fourth request after cache has been updated at last result = executeRequest(); assertTrue("Response should have been refreshed.", compare(response2, result)); }
Example 16
Source File: APRedirectHandler.java From AntennaPodSP with MIT License | 5 votes |
/** * Workaround for broken URLs in redirection. * Proper solution involves LaxRedirectStrategy() which is not available in * current API yet. */ @Override public URI getLocationURI(HttpResponse response, HttpContext context) throws org.apache.http.ProtocolException { Header h[] = response.getHeaders(LOC); if (h.length > 0) { String s = h[0].getValue(); // Fix broken URL for (int i = 0; i < CHi.length; i++) s = s.replaceAll(CHi[i], CHo[i]); // If anything had to be fixed, then replace the header if (!s.equals(h[0].getValue())) { if (AppConfig.DEBUG) Log.d(TAG, "Original URL: " + h[0].getValue()); response.setHeader(LOC, s); if (AppConfig.DEBUG) Log.d(TAG, "Fixed URL: " + s); } } // call DefaultRedirectHandler with fixed URL return super.getLocationURI(response, context); }
Example 17
Source File: HttpCommandEffectorHttpBinTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map(); BasicHttpRequest req = (BasicHttpRequest)request; String url = req.getRequestLine().getUri(); URI uri = URI.create(url); String method = req.getRequestLine().getMethod(); boolean expectsPost = uri.getPath().equals("/post"); if (expectsPost && !method.equals("POST") || !expectsPost && !method.equals("GET")) { throw new IllegalStateException("Method " + method + " not allowed on " + url); } List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8"); if (!params.isEmpty()) { j.push().at("args"); for (NameValuePair param : params) { j.put(param.getName(), param.getValue()); } j.pop(); } j.put("origin", "127.0.0.1"); j.put("url", serverUrl + url); response.setHeader("Content-Type", "application/json"); response.setStatusCode(200); response.setEntity(new StringEntity(j.toString())); }
Example 18
Source File: TestHttpRequestHandler.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { for (Header h : headers) { response.setHeader(h); } response.setStatusCode(responseCode); response.setEntity(entity); }
Example 19
Source File: MockSamlIdpServer.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
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 20
Source File: RestClient_Test.java From juneau with Apache License 2.0 | 4 votes |
@Override public void process(HttpResponse response, HttpContext context) throws HttpException,IOException { response.setHeader("B1","1"); }