Java Code Examples for org.apache.http.HttpResponse#setStatusCode()
The following examples show how to use
org.apache.http.HttpResponse#setStatusCode() .
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: CustomHttpServer.java From spydroid-ipcamera with GNU General Public License v3.0 | 6 votes |
public void handle(HttpRequest request, HttpResponse response, HttpContext arg2) throws HttpException, IOException { if (request.getRequestLine().getMethod().equals("POST")) { // Retrieve the POST content HttpEntityEnclosingRequest post = (HttpEntityEnclosingRequest) request; byte[] entityContent = EntityUtils.toByteArray(post.getEntity()); String content = new String(entityContent, Charset.forName("UTF-8")); // Execute the request final String json = RequestHandler.handle(content); // Return the response EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(json); writer.flush(); } }); response.setStatusCode(HttpStatus.SC_OK); body.setContentType("application/json; charset=UTF-8"); response.setEntity(body); } }
Example 2
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 3
Source File: HTTPTestValidationHandler.java From camel-kafka-connector with Apache License 2.0 | 6 votes |
@Override public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws IOException { lock.lock(); try { HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity(); String content = EntityUtils.toString(entity); replies.add(content); if (replies.size() == expected) { receivedExpectedMessages.signal(); } httpResponse.setStatusCode(HttpStatus.SC_OK); } finally { lock.unlock(); } }
Example 4
Source File: HttpServerUtilities.java From Repeat with Apache License 2.0 | 6 votes |
/** * Construct an HTTP redirect response. Note that this uses code 302, not 301. * * @param dest path to the destination. This is absolute path not including the domain. */ public static Void redirect(HttpAsyncExchange exchange, String dest, Map<String, String> params) throws IOException { String location = ""; try { URIBuilder builder = new URIBuilder(exchange.getRequest().getRequestLine().getUri()); builder.clearParameters(); for (Entry<String, String> entry : params.entrySet()) { builder.setParameter(entry.getKey(), entry.getValue()); } location = builder.setPath(dest).build().toString(); } catch (URISyntaxException e) { LOGGER.log(Level.WARNING, "Unable to parse request URI.", e); return prepareTextResponse(exchange, 500, "Unable to parse request URI."); } HttpResponse response = exchange.getResponse(); response.setStatusCode(302); response.addHeader("Location", location); exchange.submitResponse(new BasicAsyncResponseProducer(response)); return null; }
Example 5
Source File: MockitoTestUtils.java From joynr with Apache License 2.0 | 6 votes |
public static Answer<Void> createAnswerForHttpResponse(final int httpStatus) { Answer<Void> answerForHttpResponse = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { // We're replacing the entity by a StringEntity here, because // then the stream can be read as many times as desired. // Otherwise the entity can only be read once, which causes // problems. Somewhere it is obviously read before it is // unpacked in the test assertion. HttpEntityEnclosingRequest httpRequest = (HttpEntityEnclosingRequest) invocation.getArguments()[0]; String body = EntityUtils.toString(httpRequest.getEntity()); httpRequest.setEntity(new StringEntity(body)); HttpResponse httpResponse = (HttpResponse) invocation.getArguments()[1]; httpResponse.setStatusCode(httpStatus); return null; } }; return answerForHttpResponse; }
Example 6
Source File: ApiServer.java From cosmic with Apache License 2.0 | 5 votes |
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 7
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 8
Source File: TestHttpCallTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@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 9
Source File: LocalWebServerHttpRequestHandler.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { try { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (METHOD_GET.equals(method) || METHOD_HEAD.equals(method)) { handleRequest(request, response, METHOD_HEAD.equals(method)); } else if (METHOD_POST.equals(method)) { handleRequest(request, response, METHOD_HEAD.equals(method)); } else { throw new MethodNotSupportedException(MessageFormat.format( Messages.LocalWebServerHttpRequestHandler_UNSUPPORTED_METHOD, method)); } } catch (Exception e) { IdeLog.logError(WebServerCorePlugin.getDefault(), e); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_INTERNAL_SERVER_ERROR)); } }
Example 10
Source File: HttpServerUtilities.java From Repeat with Apache License 2.0 | 5 votes |
public static Void prepareResponse(HttpAsyncExchange exchange, int code, byte[] data) throws IOException { HttpResponse response = exchange.getResponse(); response.setStatusCode(code); response.setEntity(new ByteArrayEntity(data)); exchange.submitResponse(new BasicAsyncResponseProducer(response)); return null; }
Example 11
Source File: ClusterServiceServletHttpHandler.java From cosmic with Apache License 2.0 | 5 votes |
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 12
Source File: HttpProgressHandler.java From AndroidWebServ with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { HttpPostParser parser = new HttpPostParser(); Map<String, String> params = parser.parse(request); String id = params.get("id"); if (id == null) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); return; } String progress = Progress.get(id) + ""; if (DEBUG) Log.d(TAG, id + ": " + progress); response.setEntity(new StringEntity(progress, Config.ENCODING)); }
Example 13
Source File: PhotatoHandler.java From Photato with GNU Affero General Public License v3.0 | 5 votes |
@Override public final void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { if (!this.allowedVerbs.contains(request.getRequestLine().getMethod().toUpperCase())) { response.setStatusCode(http403.responseCode); response.setEntity(http403.entity); } else { Tuple<String, Map<String, String>> pathAndQueryTuple = PathHelper.splitPathAndQuery(request.getRequestLine().getUri().substring(this.prefix.length())); String path = pathAndQueryTuple.o1; Map<String, String> query = pathAndQueryTuple.o2; if (this.isAuthorized(path, query)) { try { Response res = getResponse(path, query); response.setStatusCode(res.responseCode); response.setHeaders(res.headers); response.setEntity(res.entity); } catch (Exception ex) { response.setStatusCode(http500.responseCode); response.setEntity(http500.entity); ex.printStackTrace(); } } else { response.setStatusCode(http403.responseCode); response.setEntity(http403.entity); } } }
Example 14
Source File: BasicValidationHandler.java From syndesis with Apache License 2.0 | 5 votes |
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (expectedMethod != null && !expectedMethod.equals(request.getRequestLine().getMethod())) { response.setStatusCode(HttpStatus.SC_METHOD_FAILURE); return; } if (!validateQuery(request)) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); return; } if (expectedContent != null) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); String content = EntityUtils.toString(entity); if (!expectedContent.equals(content)) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); return; } } response.setStatusCode(HttpStatus.SC_OK); if (responseContent != null) { response.setEntity(new StringEntity(responseContent, "ASCII")); } }
Example 15
Source File: MockSamlIdpServer.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
protected void handleSloRequest(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { if ("GET".equalsIgnoreCase(request.getRequestLine().getMethod())) { handleSloGetRequestBase(request); } else { response.setStatusCode(405); } }
Example 16
Source File: AuthHandler.java From brooklyn-server with Apache License 2.0 | 5 votes |
@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 17
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 18
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 19
Source File: ErroneousHttpHandler.java From deprecated-security-advanced-modules with Apache License 2.0 | 4 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(404); }
Example 20
Source File: MockIpdServer.java From deprecated-security-advanced-modules with Apache License 2.0 | 4 votes |
protected void handleKeysRequest(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(200); response.setEntity(new StringEntity(toJson(jwks))); }