public void receive() { EndPoint endPoint = connection.getEndPoint(); HttpClient client = connection.getHttpClient(); ByteBufferPool bufferPool = client.getByteBufferPool(); ByteBuffer buffer = bufferPool.acquire(client.getResponseBufferSize(), true); try { while (true) { // Connection may be closed in a parser callback if (connection.isClosed()) { LOG.debug("{} closed", connection); break; } else { int read = endPoint.fill(buffer); LOG.debug("Read {} bytes from {}", read, connection); if (read > 0) { parse(buffer); } else if (read == 0) { fillInterested(); break; } else { shutdown(); break; } } } } catch (EofException x) { LOG.ignore(x); failAndClose(x); } catch (Exception x) { LOG.debug(x); failAndClose(x); } finally { bufferPool.release(buffer); } }
protected boolean success() { HttpExchange exchange = connection.getExchange(); if (exchange == null) return false; AtomicMarkableReference<Result> completion = exchange.responseComplete(null); if (!completion.isMarked()) return false; parser.reset(); decoder = null; if (!updateState(State.RECEIVE, State.IDLE)) throw new IllegalStateException(); exchange.terminateResponse(); HttpResponse response = exchange.getResponse(); List<Response.ResponseListener> listeners = exchange.getConversation().getResponseListeners(); ResponseNotifier notifier = connection.getDestination().getResponseNotifier(); notifier.notifySuccess(listeners, response); LOG.debug("Received {}", response); Result result = completion.getReference(); if (result != null) { connection.complete(exchange, !result.isFailed()); notifier.notifyComplete(listeners, result); } return true; }
/* */ public void stop(int paramInt) { /* 180 */ if (paramInt < 0) { /* 181 */ throw new IllegalArgumentException("negative delay parameter"); /* */ } /* 183 */ this.terminating = true; /* */ try { this.schan.close(); } catch (IOException localIOException) { /* 185 */ }this.selector.wakeup(); /* 186 */ long l = System.currentTimeMillis() + paramInt * 1000; /* 187 */ while (System.currentTimeMillis() < l) { /* 188 */ delay(); /* 189 */ if (this.finished) { /* 190 */ break; /* */ } /* */ } /* 193 */ this.finished = true; /* 194 */ this.selector.wakeup(); /* 195 */ synchronized (this.allConnections) { /* 196 */ for (HttpConnection localHttpConnection : this.allConnections) { /* 197 */ localHttpConnection.close(); /* */ } /* */ } /* 200 */ this.allConnections.clear(); /* 201 */ this.idleConnections.clear(); /* 202 */ this.timer.cancel(); /* 203 */ if (timer1Enabled) /* 204 */ this.timer1.cancel(); /* */ }
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; }
@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; }
public void close() { if (closed) { return; } closed = true; /* close the underlying connection if, * a) the streams not set up yet, no response can be sent, or * b) if the wrapper output stream is not set up, or * c) if the close of the input/outpu stream fails */ try { if (uis_orig == null || uos == null) { connection.close(); return; } if (!uos_orig.isWrapped()) { connection.close(); return; } if (!uis_orig.isClosed()) { uis_orig.close(); } uos.close(); } catch (IOException e) { connection.close(); } }
private Image getAvatar() { HttpConnection httemp = null; InputStream istemp = null; Image avatar = null; try { httemp = (HttpConnection) Connector.open(url); if (HttpConnection.HTTP_OK != httemp.getResponseCode()) { throw new IOException(); } istemp = httemp.openInputStream(); byte[] avatarBytes = read(istemp, (int) httemp.getLength()); // #sijapp cond.if modules_TRAFFIC is "true" # Traffic.getInstance().addInTraffic(avatarBytes.length); // #sijapp cond.end# avatar = javax.microedition.lcdui.Image.createImage(avatarBytes, 0, avatarBytes.length); avatarBytes = null; } catch (Exception e) { } try { httemp.close(); istemp.close(); } catch (Exception e) { } return avatar; }
/* */ private void handleEvent(Event paramEvent) /* */ { /* 266 */ ExchangeImpl localExchangeImpl = paramEvent.exchange; /* 267 */ HttpConnection localHttpConnection = localExchangeImpl.getConnection(); /* */ try { /* 269 */ if ((paramEvent instanceof WriteFinishedEvent)) /* */ { /* 271 */ int i = ServerImpl.this.endExchange(); /* 272 */ if ((ServerImpl.this.terminating) && (i == 0)) { /* 273 */ ServerImpl.this.finished = true; /* */ } /* 275 */ ServerImpl.this.responseCompleted(localHttpConnection); /* 276 */ LeftOverInputStream localLeftOverInputStream = localExchangeImpl.getOriginalInputStream(); /* 277 */ if (!localLeftOverInputStream.isEOF()) { /* 278 */ localExchangeImpl.close = true; /* */ } /* 280 */ if ((localExchangeImpl.close) || (ServerImpl.this.idleConnections.size() >= ServerImpl.MAX_IDLE_CONNECTIONS)) { /* 281 */ localHttpConnection.close(); /* 282 */ ServerImpl.this.allConnections.remove(localHttpConnection); /* */ } /* 284 */ else if (localLeftOverInputStream.isDataBuffered()) /* */ { /* 286 */ ServerImpl.this.requestStarted(localHttpConnection); /* 287 */ handle(localHttpConnection.getChannel(), localHttpConnection); /* */ } else { /* 289 */ this.connsToRegister.add(localHttpConnection); /* */ } /* */ } /* */ } /* */ catch (IOException localIOException) { /* 294 */ ServerImpl.this.logger.log(Level.FINER, "Dispatcher (1)", localIOException); /* */ /* 297 */ localHttpConnection.close(); /* */ } /* */ }
@Override public void releaseConnectionOnIdle() throws IOException { if (canReuseConnection()) { httpConnection.poolOnIdle(); } else { httpConnection.closeOnIdle(); } }
private boolean processProxyAuthChallenge(final HttpMethod method) throws MalformedChallengeException, AuthenticationException { AuthState authstate = method.getProxyAuthState(); Map proxyChallenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders(PROXY_AUTH_CHALLENGE)); if (proxyChallenges.isEmpty()) { LOG.debug("Proxy authentication challenge(s) not found"); return false; } AuthScheme authscheme = null; try { authscheme = this.authProcessor.processChallenge(authstate, proxyChallenges); } catch (AuthChallengeException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } if (authscheme == null) { return false; } AuthScope authscope = new AuthScope( conn.getProxyHost(), conn.getProxyPort(), authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Proxy authentication scope: " + authscope); } if (authstate.isAuthAttempted() && authscheme.isComplete()) { // Already tried and failed Credentials credentials = promptForProxyCredentials(authscheme, method.getParams(), authscope); if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("Failure authenticating with " + authscope); } return false; } else { return true; } } else { authstate.setAuthAttempted(true); Credentials credentials = this.state.getProxyCredentials(authscope); if (credentials == null) { credentials = promptForProxyCredentials(authscheme, method.getParams(), authscope); } if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("No credentials available for " + authscope); } return false; } else { return true; } } }
/** * prepare the HTTP connection * * @param conn * @throws IOException */ private void configureConncetion(HttpConnection conn) throws IOException { conn.setRequestProperty("User-Agent", ua); String locale = System.getProperty("microedition.locale"); if (locale == null) { locale = "en-US"; } conn.setRequestProperty("Accept-Language", locale); conn.setRequestProperty("Content-Type", "text/json"); conn.setRequestProperty("Accept", "text/plain"); conn.setRequestProperty("appKey", "929e65a6-7a88-4c4c-a75b-d40d18cdabbb"); }
/* */ private void closeConnection(HttpConnection paramHttpConnection) { /* 455 */ paramHttpConnection.close(); /* 456 */ this.allConnections.remove(paramHttpConnection); /* 457 */ switch (1.$SwitchMap$sun$net$httpserver$HttpConnection$State[paramHttpConnection.getState().ordinal()]) { /* */ case 1: /* 459 */ this.reqConnections.remove(paramHttpConnection); /* 460 */ break; /* */ case 2: /* 462 */ this.rspConnections.remove(paramHttpConnection); /* 463 */ break; /* */ case 3: /* 465 */ this.idleConnections.remove(paramHttpConnection);
/** * 读取响应信息 * * @param httpConnection Http连接对象 * @return HttpResponse */ public static HttpResponse readResponse(HttpConnection httpConnection) { final HttpResponse httpResponse = new HttpResponse(); try { httpResponse.status = httpConnection.responseCode(); httpResponse.headers = httpConnection.headers(); httpResponse.charset = httpConnection.charset(); httpResponse.readBody(httpConnection.getInputStream()); } catch (IOException e) { throw new HttpException(e.getMessage(), e); } return httpResponse; }
@Override public Sink createRequestBody(Request request, long contentLength) throws IOException { if ("chunked".equalsIgnoreCase(request.header("Transfer-Encoding"))) { // Stream a request body of unknown length. return httpConnection.newChunkedSink(); } if (contentLength != -1) { // Stream a request body of a known length. return httpConnection.newFixedLengthSink(contentLength); } throw new IllegalStateException( "Cannot stream a request body without chunked encoding or a known content length!"); }
@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)); }
public SSLSession getSSLSession() { SSLEngine e = connection.getSSLEngine(); if (e == null) { return null; } return e.getSession(); }
public long read(OkBuffer okbuffer, long l) throws IOException { if (l < 0L) { throw new IllegalArgumentException((new StringBuilder()).append("byteCount < 0: ").append(l).toString()); } if (closed) { throw new IllegalStateException("closed"); } if (bytesRemaining == 0L) { l = -1L; } else { long l1 = HttpConnection.access$900(HttpConnection.this).read(okbuffer, Math.min(bytesRemaining, l)); if (l1 == -1L) { unexpectedEndOfInput(); throw new ProtocolException("unexpected end of stream"); } bytesRemaining = bytesRemaining - l1; cacheWrite(okbuffer, l1); l = l1; if (bytesRemaining == 0L) { endOfInput(true); return l1; } } return l; }
private void shutdown() { // Shutting down the parser may invoke messageComplete() or fail() parser.shutdownInput(); State state = this.state.get(); if (state == State.IDLE || state == State.RECEIVE) { if (!fail(new EOFException())) connection.close(); } }
/* */ void reRegister(HttpConnection paramHttpConnection) /* */ { /* */ try /* */ { /* 307 */ SocketChannel localSocketChannel = paramHttpConnection.getChannel(); /* 308 */ localSocketChannel.configureBlocking(false); /* 309 */ SelectionKey localSelectionKey = localSocketChannel.register(ServerImpl.this.selector, 1); /* 310 */ localSelectionKey.attach(paramHttpConnection); /* 311 */ paramHttpConnection.selectionKey = localSelectionKey; /* 312 */ paramHttpConnection.time = (ServerImpl.this.getTime() + ServerImpl.IDLE_INTERVAL); /* 313 */ ServerImpl.this.idleConnections.add(paramHttpConnection); /* */ } catch (IOException localIOException) { /* 315 */ ServerImpl.dprint(localIOException); /* 316 */ ServerImpl.this.logger.log(Level.FINER, "Dispatcher(8)", localIOException); /* 317 */ paramHttpConnection.close(); /* */ } /* */ }
@Override protected String doInBackground(Object... executeParams) { String url = (String) executeParams[0]; String method = (String) executeParams[2]; @SuppressWarnings("unchecked") Map<String, String> parames = (Map<String, String>) executeParams[1]; try { if (method.equals(POST)) { return HttpConnection.doPOSTMethod(url, parames); } else { return HttpConnection.doGETMethod(url, parames); } } catch (Exception e) { LogUtils.e(e.toString()); } return ""; }
/** * Prepares the HTTP headers and sends them to the server. * * <p>For streaming requests with a body, headers must be prepared <strong>before</strong> the * output stream has been written to. Otherwise the body would need to be buffered! * * <p>For non-streaming requests with a body, headers must be prepared <strong>after</strong> the * output stream has been written to and closed. This ensures that the {@code Content-Length} * header field receives the proper value. */ public void writeRequestHeaders(Request request) throws IOException { httpEngine.writingRequestHeaders(); String requestLine = RequestLine.get( request, httpEngine.getConnection().getRoute().getProxy().type(), httpEngine.getConnection().getProtocol()); httpConnection.writeRequest(request.headers(), requestLine); }
/** * Processes a new connection making it idle or active depending on whether requests are waiting * to be sent. * * <p>A new connection is created when a request needs to be executed; it is possible that the * request that triggered the request creation is executed by another connection that was just * released, so the new connection may become idle. * * <p>If a request is waiting to be executed, it will be dequeued and executed by the new * connection. * * @param connection the new connection * @param dispatch whether to dispatch the processing to another thread */ protected void process(Connection connection, boolean dispatch) { // Ugly cast, but lack of generic reification forces it final HttpConnection httpConnection = (HttpConnection) connection; final HttpExchange exchange = exchanges.poll(); if (exchange == null) { LOG.debug("{} idle", httpConnection); if (!idleConnections.offer(httpConnection)) { LOG.debug("{} idle overflow"); httpConnection.close(); } if (!client.isRunning()) { LOG.debug("{} is stopping", client); remove(httpConnection); httpConnection.close(); } } else { final Request request = exchange.getRequest(); Throwable cause = request.getAbortCause(); if (cause != null) { abort(exchange, cause); LOG.debug("Aborted before processing {}: {}", exchange, cause); } else { LOG.debug("{} active", httpConnection); if (!activeConnections.offer(httpConnection)) { LOG.warn("{} active overflow"); } if (dispatch) { client .getExecutor() .execute( new Runnable() { @Override public void run() { httpConnection.send(exchange); } }); } else { httpConnection.send(exchange); } } } }
/* */ public void run() /* */ { /* 798 */ LinkedList localLinkedList = new LinkedList(); /* 799 */ ServerImpl.this.time = System.currentTimeMillis(); /* 800 */ ServerImpl.access$1808(ServerImpl.this); /* */ Iterator localIterator; /* */ HttpConnection localHttpConnection; /* 801 */ synchronized (ServerImpl.this.idleConnections) { /* 802 */ for (localIterator = ServerImpl.this.idleConnections.iterator(); localIterator.hasNext(); ) { localHttpConnection = (HttpConnection)localIterator.next(); /* 803 */ if (localHttpConnection.time <= ServerImpl.this.time) { /* 804 */ localLinkedList.add(localHttpConnection); /* */ } /* */ } /* 807 */ for (localIterator = localLinkedList.iterator(); localIterator.hasNext(); ) { localHttpConnection = (HttpConnection)localIterator.next(); /* 808 */ ServerImpl.this.idleConnections.remove(localHttpConnection); /* 809 */ ServerImpl.this.allConnections.remove(localHttpConnection); /* 810 */ localHttpConnection.close(); } /* */ } /* */ }
private Source getTransferStream(Response response) throws IOException { if (!HttpEngine.hasBody(response)) { return httpConnection.newFixedLengthSource(0); } if ("chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { return httpConnection.newChunkedSource(httpEngine); } long contentLength = OkHeaders.contentLength(response); if (contentLength != -1) { return httpConnection.newFixedLengthSource(contentLength); } // Wrap the input stream from the connection (rather than just returning // "socketIn" directly here), so that we can control its use after the // reference escapes. return httpConnection.newUnknownLengthSource(); }
private Object request( String url, boolean post, Hashtable params, boolean basicAuth, boolean processOutput) throws Exception { HttpConnection conn = null; Writer writer = null; InputStream is = null; try { if (!post && (params != null)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos, this.encoding); this.encodeParams(params, osw); osw.flush(); osw.close(); osw = null; url += "?" + new String(baos.toByteArray(), this.encoding); baos = null; } conn = (HttpConnection) Connector.open(url); conn.setRequestMethod(post ? HttpConnection.POST : HttpConnection.GET); if (basicAuth) { if (!this.areCredentialsSet()) throw new Exception("Credentials are not set"); String token = base64Encode((this.user + ":" + this.pass).getBytes(this.encoding)); conn.setRequestProperty("Authorization", "Basic " + token); } if (post && (params != null)) { OutputStream os = conn.openOutputStream(); writer = new OutputStreamWriter(os, this.encoding); this.encodeParams(params, writer); writer.flush(); writer.close(); os = null; writer = null; } int code = conn.getResponseCode(); if ((code != 200) && (code != 302)) throw new Exception("Unexpected response code " + code + ": " + conn.getResponseMessage()); is = conn.openInputStream(); if (processOutput) { synchronized (this.json) { return this.json.parse(is); } } else { this.pump(is, System.out, 1024); return null; } } finally { if (writer != null) writer.close(); if (is != null) is.close(); if (conn != null) conn.close(); } }
/** * @param policy the HttpURLConnectionImpl with connection configuration * @param enclosing the HttpsURLConnection with HTTPS features */ private HttpsEngine( HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders, HttpConnection connection, RetryableOutputStream requestBody, HttpsURLConnectionImpl enclosing) throws IOException { super(policy, method, requestHeaders, connection, requestBody); this.sslSocket = connection != null ? connection.getSecureSocketIfConnected() : null; this.enclosing = enclosing; }
private void storeCookie(URI uri, HttpField field) { try { String value = field.getValue(); if (value != null) { Map<String, List<String>> header = new HashMap<>(1); header.put(field.getHeader().asString(), Collections.singletonList(value)); connection.getHttpClient().getCookieManager().put(uri, header); } } catch (IOException x) { LOG.debug(x); } }
/* ------------------------------------------------------------ */ protected void connectionClosed(HttpConnection connection) { if (_statsStartedAt >= 0) { long duration = System.currentTimeMillis() - connection.getTimeStamp(); int requests = connection.getRequests(); synchronized (_statsLock) { _requests += requests; _connections++; _connectionsOpen--; _connectionsDurationTotal += duration; if (_connectionsOpen < 0) _connectionsOpen = 0; if (_connectionsOpen < _connectionsOpenMin) _connectionsOpenMin = _connectionsOpen; if (_connectionsDurationMin == 0 || duration < _connectionsDurationMin) _connectionsDurationMin = duration; if (duration > _connectionsDurationMax) _connectionsDurationMax = duration; if (_connectionsRequestsMin == 0 || requests < _connectionsRequestsMin) _connectionsRequestsMin = requests; if (requests > _connectionsRequestsMax) _connectionsRequestsMax = requests; } } connection.destroy(); }