protected String getRallyXML(String apiUrl) throws Exception { String responseXML = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); Base64 base64 = new Base64(); String encodeString = new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes())); HttpGet httpGet = new HttpGet(apiUrl); httpGet.addHeader("Authorization", "Basic " + encodeString); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStreamReader reader = new InputStreamReader(entity.getContent()); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } responseXML = sb.toString(); } log.debug("responseXML=" + responseXML); return responseXML; }
public String readResponse(HttpResponse response) { String output = ""; HttpEntity entity = response.getEntity(); try { trapException(response.getStatusLine().getStatusCode()); } catch (CrowdFlowerException e1) { e1.printStackTrace(); } InputStream instream; try { instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response output = output + reader.readLine(); instream.close(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return output; }
public void run() { HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // HttpResponse response = null; // This is acting as keep alive. // while (isActive()) { try { Thread.sleep(KEEP_ALIVE_PERIOD); httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); response = null; response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status != RestStreamHanlder.SUCCESS_200) { logger.error( "Cant register to the remote client, retrying in:" + (KEEP_ALIVE_PERIOD / 1000) + " seconds."); structure = registerAndGetStructure(); } } catch (Exception e) { logger.warn(e.getMessage(), e); } finally { if (response != null) { try { response.getEntity().getContent().close(); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } } }
@Test public void testFetchContentSignedOwner() throws Exception { oauth.httpResponse = CACHEABLE; signedRequest.getOAuthArguments().setSignViewer(false); HttpResponse httpResponse = requestPipeline.execute(signedRequest); assertEquals(CACHEABLE, httpResponse); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); // Invalidate by owner only service.invalidateUserResources(ImmutableSet.of("OwnerX"), appxToken); oauth.httpResponse = new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT1").create(); httpResponse = requestPipeline.execute(signedRequest); assertEquals("NEWCONTENT1", httpResponse.getResponseAsString()); assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER)); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); // Invalidating viewer has no effect service.invalidateUserResources(ImmutableSet.of("ViewerX"), appxToken); oauth.httpResponse = new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT2").create(); httpResponse = requestPipeline.execute(signedRequest); assertEquals("NEWCONTENT1", httpResponse.getResponseAsString()); assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER)); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); }
@Override public IResponse processRequest(IRequest request) { HttpResponse httpResponse = new HttpResponse(); try { HttpRequest httpRequest = new HttpRequest(request); logger.debug( HttpRequestProcessor.class.getName(), "processRequest", "Request:\n" + new String(httpRequest.getRawData(), Charset.defaultCharset())); for (IHttpRequestHandler h : handlers) { if (h.match(httpRequest)) { h.handle(httpRequest, httpResponse); break; } } return httpResponse.build(); } catch (Exception e) { logger.error("", e); return HttpStatus.HTTP_504.response; } }
/** * Create an object (=file) * * @param containerName Name of the container * @param objectName Name of the file * @param contents Binary content of the file * @throws IOException */ public void createObject(String containerName, String objectName, byte[] contents) throws Exception { HttpURLConnection conn = getConnBuilder(containerName, objectName) .method("PUT") .addHeader(HttpHeaders.CONTENT_LENGTH_HEADER, String.valueOf(contents.length)) .getConnection(); HttpResponse response = Utils.doSendOperation(conn, contents); if (!response.isSuccessCode()) { if (response.isAuthDenied()) { log.warn("Refreshing credentials and retrying"); authenticate(); createObject(containerName, objectName, contents); } else { log.error( "Error creating object " + objectName + " in container " + containerName + ",code = " + response.code); } } }
private static void sendStatus( HttpResponse response, @Nullable HttpRequest request, Channel channel, @Nullable String description) { response.setHeader(CONTENT_TYPE, "text/html"); if (request == null || request.getMethod() != HttpMethod.HEAD) { String message = response.getStatus().toString(); StringBuilder builder = new StringBuilder(); builder .append("<!doctype html><title>") .append(message) .append("</title>") .append("<h1 style=\"text-align: center\">") .append(message) .append("</h1>"); if (description != null) { builder.append("<p>").append(description).append("</p>"); } builder .append("<hr/><p style=\"text-align: center\">") .append(StringUtil.notNullize(getServerHeaderValue(), "")) .append("</p>"); response.setContent(ChannelBuffers.copiedBuffer(builder, CharsetUtil.UTF_8)); } send(response, channel, request); }
public static void serve404( NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) { Logger.trace("serve404: begin"); HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); nettyResponse.setHeader(SERVER, signature); nettyResponse.setHeader(CONTENT_TYPE, "text/html"); Map<String, Object> binding = getBindingForErrors(e, false); String format = Request.current().format; if (format == null) { format = "txt"; } nettyResponse.setHeader( CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain"))); String errorHtml = TemplateLoader.load("errors/404." + format).render(binding); try { ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8")); nettyResponse.setContent(buf); ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse); writeFuture.addListener(ChannelFutureListener.CLOSE); } catch (UnsupportedEncodingException fex) { Logger.error(fex, "(utf-8 ?)"); } Logger.trace("serve404: end"); }
@Test public void testLargeFileRegionChunked() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); assertTrue(channel.writeOutbound(response)); ByteBuf buffer = channel.readOutbound(); assertEquals( "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertTrue(channel.writeOutbound(FILE_REGION)); buffer = channel.readOutbound(); assertEquals("80000000\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); FileRegion region = channel.readOutbound(); assertSame(FILE_REGION, region); region.release(); buffer = channel.readOutbound(); assertEquals("\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT)); buffer = channel.readOutbound(); assertEquals("0\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); buffer.release(); assertFalse(channel.finish()); }
@Override public void badMessage(int status, String reason) { HttpExchange exchange = connection.getExchange(); HttpResponse response = exchange.getResponse(); response.status(status).reason(reason); failAndClose(new HttpResponseException("HTTP protocol violation: bad response", response)); }
@Route(method = HttpRequest.Method.POST, urlPattern = "/register") public HttpResponse register( HttpRequest request, @Param("name") String name, @Param("surname") String surname, @Param("email") String email, @Param("password") String password) { User user = new User(DB.getInstance().getNewId(), name, surname, email, password); DB.getInstance().addUser(user); HttpResponse response = new HttpResponse("Successfully created an user", 200); Cookie c = new Cookie("auth", request); response.addCookie(c); String sessionId = SessionManager.getSessionIdForRequest(request); SessionManager.getInstance().addSession(sessionId, new Integer(user.id)); try { String body = TemplateProcessor.process("profile.html", user.getJsonData().build()); response.setBody(body); } catch (IOException e) { response.setStatusCode(500); } return response; }
@Override public boolean headerComplete() { if (updateState(State.RECEIVE, State.RECEIVE)) { HttpExchange exchange = connection.getExchange(); // The exchange may be null if it failed concurrently if (exchange != null) { HttpConversation conversation = exchange.getConversation(); HttpResponse response = exchange.getResponse(); LOG.debug("Headers {}", response); ResponseNotifier notifier = connection.getDestination().getResponseNotifier(); notifier.notifyHeaders(conversation.getResponseListeners(), response); Enumeration<String> contentEncodings = response.getHeaders().getValues(HttpHeader.CONTENT_ENCODING.asString(), ","); if (contentEncodings != null) { for (ContentDecoder.Factory factory : connection.getHttpClient().getContentDecoderFactories()) { while (contentEncodings.hasMoreElements()) { if (factory.getEncoding().equalsIgnoreCase(contentEncodings.nextElement())) { this.decoder = factory.newContentDecoder(); break; } } } } } } return false; }
@Override public boolean parsedHeader(HttpField field) { if (updateState(State.RECEIVE, State.RECEIVE)) { HttpExchange exchange = connection.getExchange(); // The exchange may be null if it failed concurrently if (exchange != null) { HttpConversation conversation = exchange.getConversation(); HttpResponse response = exchange.getResponse(); ResponseNotifier notifier = connection.getDestination().getResponseNotifier(); boolean process = notifier.notifyHeader(conversation.getResponseListeners(), response, field); if (process) { response.getHeaders().add(field); HttpHeader fieldHeader = field.getHeader(); if (fieldHeader != null) { switch (fieldHeader) { case SET_COOKIE: case SET_COOKIE2: { storeCookie(exchange.getRequest().getURI(), field); break; } default: { break; } } } } } } return false; }
@Override public boolean startResponse(HttpVersion version, int status, String reason) { if (updateState(State.IDLE, State.RECEIVE)) { HttpExchange exchange = connection.getExchange(); // The exchange may be null if it failed concurrently if (exchange != null) { HttpConversation conversation = exchange.getConversation(); HttpResponse response = exchange.getResponse(); String method = exchange.getRequest().method(); parser.setHeadResponse(HttpMethod.HEAD.is(method) || HttpMethod.CONNECT.is(method)); response.version(version).status(status).reason(reason); // Probe the protocol handlers HttpClient client = connection.getHttpClient(); ProtocolHandler protocolHandler = client.findProtocolHandler(exchange.getRequest(), response); Response.Listener handlerListener = null; if (protocolHandler != null) { handlerListener = protocolHandler.getResponseListener(); LOG.debug("Found protocol handler {}", protocolHandler); } exchange.getConversation().updateResponseListeners(handlerListener); LOG.debug("Receiving {}", response); ResponseNotifier notifier = connection.getDestination().getResponseNotifier(); notifier.notifyBegin(conversation.getResponseListeners(), response); } } return false; }
private HttpResponse _send() { if (httpConnection == null) { open(); } // sends data HttpResponse httpResponse; try { OutputStream outputStream = httpConnection.getOutputStream(); sendTo(outputStream); InputStream inputStream = httpConnection.getInputStream(); httpResponse = HttpResponse.readFrom(inputStream); httpResponse.assignHttpRequest(this); } catch (IOException ioex) { throw new HttpException(ioex); } boolean keepAlive = httpResponse.isConnectionPersistent(); if (!keepAlive) { // closes connection if keep alive is false, or if counter reached 0 httpConnection.close(); httpConnection = null; } return httpResponse; }
public static JsonErrorResponse fromResponse(HttpResponse response) throws IOException { int statusCode = response.getStatusCode(); // parse error body Map<String, String> map = JsonUtils.jsonToMap(new BufferedReader(new InputStreamReader(response.getContent()))); /* * Services using AWS JSON 1.1 protocol with HTTP binding send the * error type information in the response headers, instead of the * content. */ String errorCode = response.getHeaders().get(X_AMZN_ERROR_TYPE); if (errorCode != null) { int separator = errorCode.indexOf(':'); if (separator != -1) { errorCode = errorCode.substring(0, separator); } } else if (map.containsKey("__type")) { // check body otherwise String type = map.get("__type"); int separator = type.lastIndexOf("#"); errorCode = type.substring(separator + 1); } return new JsonErrorResponse(statusCode, errorCode, map); }
protected static void addToResponse(Response response, HttpResponse nettyResponse) { Map<String, Http.Header> headers = response.headers; for (Map.Entry<String, Http.Header> entry : headers.entrySet()) { Http.Header hd = entry.getValue(); for (String value : hd.values) { nettyResponse.setHeader(entry.getKey(), value); } } Map<String, Http.Cookie> cookies = response.cookies; for (Http.Cookie cookie : cookies.values()) { CookieEncoder encoder = new CookieEncoder(true); Cookie c = new DefaultCookie(cookie.name, cookie.value); c.setSecure(cookie.secure); c.setPath(cookie.path); if (cookie.domain != null) { c.setDomain(cookie.domain); } if (cookie.maxAge != null) { c.setMaxAge(cookie.maxAge); } c.setHttpOnly(cookie.httpOnly); encoder.addCookie(c); nettyResponse.addHeader(SET_COOKIE, encoder.encode()); } if (!response.headers.containsKey(CACHE_CONTROL)) { nettyResponse.setHeader(CACHE_CONTROL, "no-cache"); } }
@Override public AmazonServiceException handle(HttpResponse response) throws Exception { JsonErrorResponse error; try { error = JsonErrorResponse.fromResponse(response); } catch (IOException e) { throw new AmazonClientException("Unable to parse error response", e); } AmazonServiceException ase = runErrorUnmarshallers(error); if (ase == null) return null; ase.setStatusCode(response.getStatusCode()); if (response.getStatusCode() < 500) { ase.setErrorType(ErrorType.Client); } else { ase.setErrorType(ErrorType.Service); } ase.setErrorCode(error.getErrorCode()); for (Entry<String, String> headerEntry : response.getHeaders().entrySet()) { if (headerEntry.getKey().equalsIgnoreCase("X-Amzn-RequestId")) { ase.setRequestId(headerEntry.getValue()); } } return ase; }
/* Exception reporting policy method. * @param e the Throwable to report. */ private void exception(Throwable e) { try { _persistent = false; int error_code = HttpResponse.__500_Internal_Server_Error; if (e instanceof HttpException) { error_code = ((HttpException) e).getCode(); if (_request == null) log.warn(e.toString()); else log.warn(_request.getRequestLine() + " " + e.toString()); log.debug(LogSupport.EXCEPTION, e); } else if (e instanceof EOFException) { LogSupport.ignore(log, e); return; } else { _request.setAttribute("javax.servlet.error.exception_type", e.getClass()); _request.setAttribute("javax.servlet.error.exception", e); if (_request == null) log.warn(LogSupport.EXCEPTION, e); else log.warn(_request.getRequestLine(), e); } if (_response != null && !_response.isCommitted()) { _response.reset(); _response.removeField(HttpFields.__TransferEncoding); _response.setField(HttpFields.__Connection, HttpFields.__Close); _response.sendError(error_code); } } catch (Exception ex) { LogSupport.ignore(log, ex); } }
public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http:'//twitter.com/users/show/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readline()) != null) { builder.append(line); } } else { Log.e(MainActivity2.class.toString(), "Failed to download file"); } } catch (ClientProtocolExpcetion e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
protected void assertCodeMakes( String method, URI uri, int statusCode, String message, String contentType, String content, Class<? extends Exception> expected) { HttpErrorHandler function = Guice.createInjector(new SaxParserModule()).getInstance(getHandlerClass()); HttpCommand command = createMock(HttpCommand.class); HttpRequest request = new HttpRequest(method, uri); HttpResponse response = new HttpResponse(statusCode, message, Payloads.newStringPayload(content)); if (contentType != null) response.getPayload().getContentMetadata().setContentType(contentType); expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); command.setException(classEq(expected)); replay(command); function.handleError(command, response); verify(command); }
private void sendExpect100(Map headers, RequestLine requestLine) throws TransformerException, IOException { // respond with status code 100, for Expect handshake // according to rfc 2616 and http 1.1 // the processing will continue and the request will be fully // read immediately after if (HttpConstants.HTTP11.equals(headers.get(HttpConnector.HTTP_VERSION_PROPERTY))) { // just in case we have something other than String in // the headers map String expectHeaderValue = ObjectUtils.toString(headers.get(HttpConstants.HEADER_EXPECT)).toLowerCase(); if (HttpConstants.HEADER_EXPECT_CONTINUE_REQUEST_VALUE.equals(expectHeaderValue)) { HttpResponse expected = new HttpResponse(); expected.setStatusLine(requestLine.getHttpVersion(), HttpConstants.SC_CONTINUE); final DefaultMuleEvent event = new DefaultMuleEvent( new DefaultMuleMessage(expected), endpoint, new DefaultMuleSession(service, connector.getMuleContext()), true); RequestContext.setEvent(event); conn.writeResponse(transformResponse(expected)); } } }
private HttpResponse executeRequest( final Callable<HttpResponse> task, final long timeout, final TimeUnit unit) throws TimeoutException, IOException { ExecutorService executor = Executors.newSingleThreadExecutor(); try { Throwable lastCause = null; long endTime = System.currentTimeMillis() + unit.toMillis(timeout); while (System.currentTimeMillis() < endTime) { Future<HttpResponse> result = executor.submit(task); try { return result.get(timeout, unit); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } catch (ExecutionException ex) { lastCause = ex.getCause(); // HttpURLConnection throws FileNotFoundException on 404 so handle this if (lastCause instanceof FileNotFoundException) { HttpResponse httpResult = new HttpResponse(); httpResult.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND); return httpResult; } else { continue; } } } TimeoutException toex = new TimeoutException(); if (lastCause != null) { toex.initCause(lastCause); } throw toex; } finally { executor.shutdownNow(); } }
protected HttpResponse buildFailureResponse(RequestLine requestLine, MuleMessage message) throws TransformerException { EndpointURI uri = endpoint.getEndpointURI(); String failedPath = uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + message.getProperty(HttpConnector.HTTP_REQUEST_PATH_PROPERTY); if (logger.isDebugEnabled()) { logger.debug("Failed to bind to " + failedPath); } HttpResponse response = new HttpResponse(); response.setStatusLine(requestLine.getHttpVersion(), HttpConstants.SC_NOT_FOUND); response.setBody(HttpMessages.cannotBindToAddress(failedPath).toString()); RequestContext.setEvent( new DefaultMuleEvent( new DefaultMuleMessage(response), endpoint, new DefaultMuleSession(service, connector.getMuleContext()), true)); // The DefaultResponseTransformer will set the necessary headers return transformResponse(response); }
@Test public void testFetchContentWithMarker() throws Exception { oauth.httpResponse = CACHEABLE; // First entry added to cache is unmarked HttpResponse httpResponse = requestPipeline.execute(signedRequest); assertEquals(CACHEABLE, httpResponse); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); // Invalidate content for OwnerX. Next entry will have owner mark service.invalidateUserResources(ImmutableSet.of("OwnerX"), appxToken); oauth.httpResponse = new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT1").create(); httpResponse = requestPipeline.execute(signedRequest); assertEquals("NEWCONTENT1", httpResponse.getResponseAsString()); assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER)); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); // Invalidate content for ViewerX. Next entry will have both owner and viewer mark service.invalidateUserResources(ImmutableSet.of("ViewerX"), appxToken); oauth.httpResponse = new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT2").create(); httpResponse = requestPipeline.execute(signedRequest); assertEquals("NEWCONTENT2", httpResponse.getResponseAsString()); assertEquals( "o=1;v=2;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER)); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); }
private boolean fetchApp(String url, String username, String password) throws JSONException { try { if (username == "null") { username = null; } if (password == "null") { password = null; } HttpResponse response = makeRequest(url, username, password); StatusLine sl = response.getStatusLine(); int code = sl.getStatusCode(); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); if (code != 200) { return false; } else { ZipInputStream data = new ZipInputStream(content); return saveAndVerify(data); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
/** * Converts an exception raised while processing an HTTP request into a suitable HTTP response. * * <p>The response is marshalled and queued for writing on the socket associated with the original * request. * * @param msg The HTTP request being processed when the exception occurred. * @param e The exception that was raised. * @throws IOException if an error occurs marshalling or writing the response. */ protected void handleMessageException(HttpMessageBuffer msg, Exception e) throws IOException { HttpResponse httpRsp; if (e instanceof HttpResponseException) { if (log.logWarn()) { log.warn("HttpResponseException", e); } httpRsp = this.newHttpResponse(msg, (HttpResponseException) e); this.queueWrite(msg.getSocket(), httpRsp.marshal(), true); } else if (e instanceof RemoteSocketClosedException) { if (log.logTrace()) { log.trace("Remote entity closed connection", e); } } else { if (log.logError()) { log.error("Internal Server Error", e); } httpRsp = this.newHttpResponse( msg, new HttpResponseException( HttpConstants.StatusCodes._500_INTERNAL_SERVER_ERROR, "Internal Server Error", e)); this.queueWrite(msg.getSocket(), httpRsp.marshal(), true); } }
/** * Continues using the same keep-alive connection. Don't use any variant of <code>open()</code> * when continuing the communication! First it checks if "Connection" header exist in the response * and if it is equal to "Keep-Alive" value. Then it checks the "Keep-Alive" headers "max" * parameter. If its value is positive, then the existing {@link jodd.http.HttpConnection} from * the request will be reused. If max value is 1, connection will be sent with "Connection: Close" * header, indicating its the last request. When new connection is created, the same {@link * jodd.http.HttpConnectionProvider} that was used for creating initial connection is used for * opening the new connection. * * @param doContinue set it to <code>false</code> to indicate the last connection */ public HttpRequest keepAlive(HttpResponse httpResponse, boolean doContinue) { boolean keepAlive = httpResponse.isConnectionPersistent(); if (keepAlive) { HttpConnection previousConnection = httpResponse.getHttpRequest().httpConnection; if (previousConnection != null) { // keep using the connection! this.httpConnection = previousConnection; this.httpConnectionProvider = httpResponse.getHttpRequest().connectionProvider(); } // keepAlive = true; (already set) } else { // close previous connection httpResponse.close(); // force keep-alive on new request keepAlive = true; } // if we don't want to continue with this persistent session, mark this connection as closed if (!doContinue) { keepAlive = false; } connectionKeepAlive(keepAlive); // if connection is not opened, open it using previous connection provider if (httpConnection == null) { open(httpResponse.getHttpRequest().connectionProvider()); } return this; }
/** * Perform an analyze of a given HttpResponse object's response-code in order to interpret whether * the requests to Twitter API went well. Otherwise, an exception is thrown describing the * problem. * * @param response HttpResponse object to be interpreted. * @throws IOException If an I/O or service error occurs. * @throws LimitExceededException If a request limit exceeded error occurs. * @throws InvalidQueryException If an invalid query error occurs. * @throws SecurityException If a security error occurs. * @throws IllegalArgumentException If response is null. */ public static void perform(HttpResponse response) throws IOException, LimitExceededException { if (response == null) { throw new IllegalArgumentException("Response must not be null."); } // final int respCode = response.getCode(); // if (respCode != HttpConnection.HTTP_OK && respCode != HttpConnection.HTTP_NOT_MODIFIED) { if (isInvalidQueryError(respCode)) { throw new InvalidQueryException(getErrorMessage(response)); } else if (isLimitExceededError(respCode)) { String emgs = getErrorMessage(response); String raft = response.getResponseField("X-Rate-Limit-Reset"); // if (!StringUtil.isEmpty(raft)) { emgs += " / Retry after " + raft + " secs."; } // throw new LimitExceededException(emgs); } else if (isSecurityError(respCode)) { throw new SecurityException(getErrorMessage(response)); } else { throw new IOException(getErrorMessage(response)); } } }
private String sendBasic(HttpRequestBase request) throws HttpException { try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = ""; if (entity != null) { body = EntityUtils.toString(entity, UTF_8); if (entity.getContentType() == null) { body = new String(body.getBytes(ISO_8859_1), UTF_8); } } int code = response.getStatusLine().getStatusCode(); if (code < 200 || code >= 300) { throw new Exception(String.format(" code : '%s' , body : '%s'", code, body)); } return body; } catch (Exception ex) { throw new HttpException( "Fail to send " + request.getMethod() + " request to url " + request.getURI() + ", " + ex.getMessage(), ex); } finally { request.releaseConnection(); } }