Here are the examples of the java api org.apache.http.params.HttpParams taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
114 Examples
19
Source : TestHttpClient.java
with Apache License 2.0
from quarkusio
with Apache License 2.0
from quarkusio
@Override
protected HttpParams createHttpParams() {
HttpParams params = super.createHttpParams();
HttpConnectionParams.setSoTimeout(params, 30000);
return params;
}
19
Source : NTLMSchemeFactory.java
with BSD 2-Clause "Simplified" License
from PushFish
with BSD 2-Clause "Simplified" License
from PushFish
public AuthScheme newInstance(HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
19
Source : SlowHC4SocketFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
// Override all the super-clreplaced Socket methods.
@Override
public Socket createSocket(final HttpParams params) {
return new SlowSocket(CPS);
}
19
Source : HC4TrustAllSSLSocketFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
/* (non-Javadoc)
* @see org.apache.http.conn.ssl.SSLSocketFactory#createSocket(org.apache.http.params.HttpParams)
*/
@Override
public Socket createSocket(HttpParams params) throws IOException {
return factory.createSocket();
}
19
Source : LazySchemeSocketFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
/**
* @param params
* @return the socket
* @throws IOException
* @see org.apache.http.conn.scheme.SchemeSocketFactory#createSocket(org.apache.http.params.HttpParams)
*/
@Override
public Socket createSocket(HttpParams params) throws IOException {
return AdapteeHolder.getINSTANCE().createSocket(params);
}
19
Source : FixedSPNegoSchemeFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
@Override
public AuthScheme newInstance(HttpParams params) {
return new FixedSPNegoScheme(isStripPort(), isUseCanonicalHostname());
}
19
Source : HttpAsyncClient.java
with MIT License
from hubcarl
with MIT License
from hubcarl
public clreplaced HttpAsyncClient extends AsyncTask<String, String, String> {
private String url;
private HttpParams httpParams;
private HttpMethod httpMethod;
private HttpResponseCallback httpResponseCallback;
public HttpAsyncClient(String url, HttpParams params, HttpResponseCallback httpResponseCallback) {
Log.i(">>>HttpAsyncClient url:", url);
this.url = url;
this.httpParams = params;
this.httpMethod = HttpMethod.GET;
this.httpResponseCallback = httpResponseCallback;
}
public HttpAsyncClient(HttpMethod method, String url, HttpParams params, HttpResponseCallback httpResponseCallback) {
this.url = url;
this.httpParams = params;
this.httpMethod = method;
this.httpResponseCallback = httpResponseCallback;
}
@Override
protected String doInBackground(String... params) {
if (HttpMethod.GET.equals(httpMethod)) {
return HttpSyncClient.httpGet(url, httpParams);
} else
return HttpSyncClient.httpPost(url, httpParams);
}
@Override
protected void onPostExecute(String response) {
Log.i(">>>response:", response);
if (Strings.EMPTY_STRING.equals(response)) {
httpResponseCallback.onError(response);
} else {
httpResponseCallback.onSuccess(response);
}
super.onPostExecute(response);
}
}
19
Source : SPNegoSchemeFactory.java
with Apache License 2.0
from Axway
with Apache License 2.0
from Axway
public AuthScheme newInstance(final HttpParams params) {
return new SPNegoScheme(gssClient, servicePrincipalName, servicePrincipalOid);
}
19
Source : SolrPortAwareCookieSpecFactory.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Override
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
final Collection<?> param = (Collection<?>) params.getParameter(CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
return new PortAwareCookieSpec(patterns);
} else {
return new PortAwareCookieSpec(null);
}
}
19
Source : Response.java
with BSD 3-Clause "New" or "Revised" License
from amihaiemil
with BSD 3-Clause "New" or "Revised" License
from amihaiemil
@Override
public void setParams(final HttpParams params) {
throw new UnsupportedOperationException("Not supported yet.");
}
18
Source : Tools.java
with Apache License 2.0
from shunfei
with Apache License 2.0
from shunfei
private static boolean stopRealtime(MyOptions options, IndexRConfig config) throws Exception {
String host = options.host == null ? InetAddress.getLocalHost().getHostName() : options.host;
int port = options.port == 0 ? config.getControlPort() : options.port;
if (options.table == null) {
sendCommand(host, port, "cmd=stoprt");
} else {
HttpParams params = new BasicHttpParams();
sendCommand(host, port, "cmd=stoprt&table=" + options.table);
}
return true;
}
18
Source : HttpResponseProxy.java
with MIT License
from PawelAdamski
with MIT License
from PawelAdamski
/**
* @deprecated
*/
@Deprecated
public void setParams(HttpParams params) {
this.original.setParams(params);
}
18
Source : HttpClientMock.java
with MIT License
from PawelAdamski
with MIT License
from PawelAdamski
public clreplaced HttpClientMock extends CloseableHttpClient {
private final HttpParams params = new BasicHttpParams();
private final Debugger debugger;
private final List<RuleBuilder> rulesUnderConstruction = new ArrayList<>();
private final List<Rule> rules = new ArrayList<>();
private final String defaultHost;
private final List<Request> requests = new ArrayList<>();
private boolean isDebuggingTurnOn = false;
private final List<HttpRequestInterceptor> requestInterceptors = new ArrayList<>();
private final List<HttpResponseInterceptor> responseInterceptors = new ArrayList<>();
/**
* Creates mock of Apache HttpClient
*/
public HttpClientMock() {
this("");
}
/**
* Creates mock of Apache HttpClient with default host. All defined conditions without host will use default host
*
* @param defaultHost default host for later conditions
*/
public HttpClientMock(String defaultHost) {
this(defaultHost, new Debugger());
}
/**
* Creates mock of Apache HttpClient with default host. All defined conditions without host will use default host
*
* @param defaultHost default host for later conditions
* @param debugger debugger used for testing
*/
HttpClientMock(String defaultHost, Debugger debugger) {
this.defaultHost = defaultHost;
this.debugger = debugger;
}
/**
* Resets mock to initial state where there are no rules and no previous requests.
*/
public void reset() {
this.rulesUnderConstruction.clear();
this.rules.clear();
this.requests.clear();
}
/**
* Creates verification builder.
*
* @return request number verification builder
*/
public HttpClientVerify verify() {
return new HttpClientVerify(defaultHost, requests);
}
/**
* Starts defining new rule which requires HTTP POST method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPost() {
return newRule(HttpPost.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP GET method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onGet() {
return newRule(HttpGet.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP DELETE method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onDelete() {
return newRule(HttpDelete.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP HEAD method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onHead() {
return newRule(HttpHead.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP OPTIONS method.
*
* @return HttpClientMockBuilder which allows to define new rule
* @deprecated Method name contains misspelling, use {@link #onOptions}
*/
@Deprecated
public HttpClientMockBuilder onOption() {
return onOptions();
}
/**
* Starts defining new rule which requires HTTP OPTIONS method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onOptions() {
return newRule(HttpOptions.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP PUT method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPut() {
return newRule(HttpPut.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP PATCH method.
*
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPatch() {
return newRule(HttpPatch.METHOD_NAME);
}
/**
* Starts defining new rule which requires HTTP GET method and url. If provided url starts with "/" request url must be equal to concatenation of default host
* and url. Otherwise request url must equal to provided url. If provided url contains query parameters and/or reference they are parsed and added as a
* separate conditions. <p> For example:<br> <code> httpClientMock.onGet("http://localhost/login?user=Ben#edit"); </code> <br>is equal to<br> <code>
* httpClientMock.onGet("http://localhost/login").withParameter("user","Ben").withReference("edit); </code>
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onGet(String url) {
return newRule(HttpGet.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP POST method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPost(String url) {
return newRule(HttpPost.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP PUT method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPut(String url) {
return newRule(HttpPut.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP DELETE method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onDelete(String url) {
return newRule(HttpDelete.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP HEAD method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onHead(String url) {
return newRule(HttpHead.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP OPTIONS method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onOptions(String url) {
return newRule(HttpOptions.METHOD_NAME, url);
}
/**
* Starts defining new rule which requires HTTP PATCH method and url. URL works the same way as in {@link #onGet(String) onGet}
*
* @param url required url
* @return HttpClientMockBuilder which allows to define new rule
*/
public HttpClientMockBuilder onPatch(String url) {
return newRule(HttpPatch.METHOD_NAME, url);
}
private HttpClientMockBuilder newRule(String method) {
RuleBuilder r = new RuleBuilder(method);
rulesUnderConstruction.add(r);
return new HttpClientMockBuilder(r);
}
private HttpClientMockBuilder newRule(String method, String url) {
RuleBuilder r = new RuleBuilder(method, defaultHost, url);
rulesUnderConstruction.add(r);
return new HttpClientMockBuilder(r);
}
@Override
protected CloseableHttpResponse doExecute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException {
finishBuildingRules();
executeRequestInterceptors(httpRequest, httpContext);
HttpResponse response = getHttpResponse(httpHost, httpRequest, httpContext);
executeResponseInterceptors(httpContext, response);
return new HttpResponseProxy(response);
}
private void executeResponseInterceptors(HttpContext httpContext, HttpResponse response) throws IOException {
try {
for (HttpResponseInterceptor responseInterceptor : responseInterceptors) {
responseInterceptor.process(response, httpContext);
}
} catch (HttpException e) {
throw new IOException(e);
}
}
private HttpResponse getHttpResponse(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException {
Request request = new Request(httpHost, httpRequest, httpContext);
requests.add(request);
Rule rule = rules.stream().filter(r -> r.matches(httpHost, httpRequest, httpContext)).reduce((a, b) -> b).orElse(Rule.NOT_FOUND);
if (isDebuggingTurnOn || rule == Rule.NOT_FOUND) {
debugger.debug(rules, request);
}
return rule.nextResponse(request);
}
private void executeRequestInterceptors(HttpRequest httpRequest, HttpContext httpContext) throws IOException {
try {
for (HttpRequestInterceptor requestInterceptor : requestInterceptors) {
requestInterceptor.process(httpRequest, httpContext);
}
} catch (HttpException e) {
throw new IOException(e);
}
}
private void finishBuildingRules() {
synchronized (rulesUnderConstruction) {
for (RuleBuilder ruleBuilder : rulesUnderConstruction) {
rules.add(ruleBuilder.toRule());
}
rulesUnderConstruction.clear();
}
}
@Override
public void close() throws IOException {
}
@Override
public HttpParams getParams() {
return params;
}
@Override
public ClientConnectionManager getConnectionManager() {
return null;
}
public void debugOn() {
isDebuggingTurnOn = true;
}
public void debugOff() {
isDebuggingTurnOn = false;
}
public void addRequestInterceptor(HttpRequestInterceptor requestInterceptor) {
this.requestInterceptors.add(requestInterceptor);
}
public void addResponseInterceptor(HttpResponseInterceptor responseInterceptor) {
this.responseInterceptors.add(responseInterceptor);
}
}
18
Source : ProxyingHttpClient.java
with Apache License 2.0
from ngageoint
with Apache License 2.0
from ngageoint
/**
* Attempts to configure the proxy to the given URI in the HTTP parameters.
*
* @param params the HTTP parameters in which the proxy configuration will
* be stored.
* @param uriString the requested URI string.
* @throws IOException if an error occurs while determining the proxy
* server.
*/
protected void configureProxy(final HttpParams params, final String uriString) throws IOException {
try {
configureProxy(params, new URI(uriString));
} catch (final URISyntaxException e) {
LOGGER.warn("Failed to convert '" + uriString + "' to a URI. The proxy will not be configured.", e);
}
}
18
Source : StreamServerImpl.java
with GNU General Public License v2.0
from newPersonKing
with GNU General Public License v2.0
from newPersonKing
/**
* Implementation based on <a href="http://hc.apache.org/">Apache HTTP Components 4.2</a>.
* <p>
* This implementation <em>DOES NOT WORK</em> on Android. Read the Cling manual for
* alternatives on Android.
* </p>
*
* @author Christian Bauer
*/
public clreplaced StreamServerImpl implements StreamServer<StreamServerConfigurationImpl> {
final private static Logger log = Logger.getLogger(StreamServer.clreplaced.getName());
final protected StreamServerConfigurationImpl configuration;
protected Router router;
protected ServerSocket serverSocket;
protected HttpParams globalParams = new BasicHttpParams();
private volatile boolean stopped = false;
public StreamServerImpl(StreamServerConfigurationImpl configuration) {
this.configuration = configuration;
}
public StreamServerConfigurationImpl getConfiguration() {
return configuration;
}
synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {
try {
this.router = router;
this.serverSocket = new ServerSocket(configuration.getListenPort(), configuration.getTcpConnectionBacklog(), bindAddress);
log.info("Created socket (for receiving TCP streams) on: " + serverSocket.getLocalSocketAddress());
this.globalParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configuration.getDataWaitTimeoutSeconds() * 1000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, configuration.getBufferSizeKilobytes() * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, configuration.isStaleConnectionCheck()).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, configuration.isTcpNoDelay());
} catch (Exception ex) {
throw new InitializationException("Could not initialize " + getClreplaced().getSimpleName() + ": " + ex.toString(), ex);
}
}
synchronized public int getPort() {
return this.serverSocket.getLocalPort();
}
synchronized public void stop() {
stopped = true;
try {
serverSocket.close();
} catch (IOException ex) {
log.fine("Exception closing streaming server socket: " + ex);
}
}
public void run() {
log.fine("Entering blocking receiving loop, listening for HTTP stream requests on: " + serverSocket.getLocalSocketAddress());
while (!stopped) {
try {
// Block until we have a connection
final Socket clientSocket = serverSocket.accept();
// We have to force this fantastic library to accept HTTP methods which are not in the holy RFCs.
final DefaultHttpServerConnection httpServerConnection = new DefaultHttpServerConnection() {
@Override
protected HttpRequestFactory createHttpRequestFactory() {
return new UpnpHttpRequestFactory();
}
};
log.fine("Incoming connection from: " + clientSocket.getInetAddress());
httpServerConnection.bind(clientSocket, globalParams);
// Wrap the processing of the request in a UpnpStream
UpnpStream connectionStream = new HttpServerConnectionUpnpStream(router.getProtocolFactory(), httpServerConnection, globalParams) {
@Override
protected Connection createConnection() {
return new ApacheServerConnection(clientSocket, httpServerConnection);
}
};
router.received(connectionStream);
} catch (InterruptedIOException ex) {
log.fine("I/O has been interrupted, stopping receiving loop, bytes transfered: " + ex.bytesTransferred);
break;
} catch (SocketException ex) {
if (!stopped) {
// That's not good, could be anything
log.fine("Exception using server socket: " + ex.getMessage());
} else {
// Well, it's just been stopped so that's totally fine and expected
}
break;
} catch (IOException ex) {
log.fine("Exception initializing receiving loop: " + ex.getMessage());
break;
}
}
try {
log.fine("Receiving loop stopped");
if (!serverSocket.isClosed()) {
log.fine("Closing streaming server socket");
serverSocket.close();
}
} catch (Exception ex) {
log.info("Exception closing streaming server socket: " + ex.getMessage());
}
}
/**
* Writes a space character to the output stream of the socket.
* <p>
* This space character might confuse the HTTP client. The Cling transports for Jetty Client and
* Apache HttpClient have been tested to work with space characters. Unfortunately, Sun JDK's
* HttpURLConnection does not gracefully handle any garbage in the HTTP request!
* </p>
*/
protected boolean isConnectionOpen(Socket socket) {
return isConnectionOpen(socket, " ".getBytes());
}
protected boolean isConnectionOpen(Socket socket, byte[] heartbeat) {
if (log.isLoggable(Level.FINE))
log.fine("Checking if client connection is still open on: " + socket.getRemoteSocketAddress());
try {
socket.getOutputStream().write(heartbeat);
socket.getOutputStream().flush();
return true;
} catch (IOException ex) {
if (log.isLoggable(Level.FINE))
log.fine("Client connection has been closed: " + socket.getRemoteSocketAddress());
return false;
}
}
protected clreplaced ApacheServerConnection implements Connection {
protected Socket socket;
protected DefaultHttpServerConnection connection;
public ApacheServerConnection(Socket socket, DefaultHttpServerConnection connection) {
this.socket = socket;
this.connection = connection;
}
@Override
public boolean isOpen() {
return isConnectionOpen(socket);
}
@Override
public InetAddress getRemoteAddress() {
return connection.getRemoteAddress();
}
@Override
public InetAddress getLocalAddress() {
return connection.getLocalAddress();
}
}
}
18
Source : StreamClientImpl.java
with GNU General Public License v2.0
from newPersonKing
with GNU General Public License v2.0
from newPersonKing
/**
* Implementation based on <a href="http://hc.apache.org/">Apache HTTP Components 4.2</a>.
* <p>
* This implementation <em>DOES NOT WORK</em> on Android. Read the Cling manual for
* alternatives on Android.
* </p>
*
* @author Christian Bauer
*/
public clreplaced StreamClientImpl extends AbstractStreamClient<StreamClientConfigurationImpl, HttpUriRequest> {
final private static Logger log = Logger.getLogger(StreamClient.clreplaced.getName());
final protected StreamClientConfigurationImpl configuration;
final protected PoolingClientConnectionManager clientConnectionManager;
final protected DefaultHttpClient httpClient;
final protected HttpParams globalParams = new BasicHttpParams();
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
this.configuration = configuration;
HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
HttpProtocolParams.setUseExpectContinue(globalParams, false);
// These are some safety settings, we should never run into these timeouts as we
// do our own expiration checking
HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000);
HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000);
HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
if (getConfiguration().getSocketBufferSize() != -1)
HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());
// Only register 80, not 443 and SSL
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
clientConnectionManager = new PoolingClientConnectionManager(registry);
clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());
httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
if (getConfiguration().getRequestRetryCount() != -1) {
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false));
}
}
@Override
public StreamClientConfigurationImpl getConfiguration() {
return configuration;
}
@Override
protected HttpUriRequest createRequest(StreamRequestMessage requestMessage) {
UpnpRequest requestOperation = requestMessage.getOperation();
HttpUriRequest request;
switch(requestOperation.getMethod()) {
case GET:
request = new HttpGet(requestOperation.getURI());
break;
case SUBSCRIBE:
request = new HttpGet(requestOperation.getURI()) {
@Override
public String getMethod() {
return UpnpRequest.Method.SUBSCRIBE.getHttpName();
}
};
break;
case UNSUBSCRIBE:
request = new HttpGet(requestOperation.getURI()) {
@Override
public String getMethod() {
return UpnpRequest.Method.UNSUBSCRIBE.getHttpName();
}
};
break;
case POST:
HttpEnreplacedyEnclosingRequest post = new HttpPost(requestOperation.getURI());
post.setEnreplacedy(createHttpRequestEnreplacedy(requestMessage));
// Fantastic API
request = (HttpUriRequest) post;
break;
case NOTIFY:
HttpEnreplacedyEnclosingRequest notify = new HttpPost(requestOperation.getURI()) {
@Override
public String getMethod() {
return UpnpRequest.Method.NOTIFY.getHttpName();
}
};
notify.setEnreplacedy(createHttpRequestEnreplacedy(requestMessage));
// Fantastic API
request = (HttpUriRequest) notify;
break;
default:
throw new RuntimeException("Unknown HTTP method: " + requestOperation.getHttpMethodName());
}
// Headers
request.setParams(getRequestParams(requestMessage));
HeaderUtil.add(request, requestMessage.getHeaders());
return request;
}
@Override
protected Callable<StreamResponseMessage> createCallable(final StreamRequestMessage requestMessage, final HttpUriRequest request) {
return new Callable<StreamResponseMessage>() {
public StreamResponseMessage call() throws Exception {
if (log.isLoggable(Level.FINE))
log.fine("Sending HTTP request: " + requestMessage);
return httpClient.execute(request, createResponseHandler());
}
};
}
@Override
protected void abort(HttpUriRequest request) {
request.abort();
}
@Override
protected boolean logExecutionException(Throwable t) {
if (t instanceof IllegalStateException) {
// TODO: Doreplacedent when/why this happens and why we can ignore it, violating the
// logging rules of the StreamClient#sendRequest() method
if (log.isLoggable(Level.FINE))
log.fine("Illegal state: " + t.getMessage());
return true;
}
return false;
}
@Override
public void stop() {
if (log.isLoggable(Level.FINE))
log.fine("Shutting down HTTP client connection manager/pool");
clientConnectionManager.shutdown();
}
protected HttpEnreplacedy createHttpRequestEnreplacedy(UpnpMessage upnpMessage) {
if (upnpMessage.getBodyType().equals(UpnpMessage.BodyType.BYTES)) {
if (log.isLoggable(Level.FINE))
log.fine("Preparing HTTP request enreplacedy as byte[]");
return new ByteArrayEnreplacedy(upnpMessage.getBodyBytes());
} else {
if (log.isLoggable(Level.FINE))
log.fine("Preparing HTTP request enreplacedy as string");
try {
String charset = upnpMessage.getContentTypeCharset();
return new StringEnreplacedy(upnpMessage.getBodyString(), charset != null ? charset : "UTF-8");
} catch (Exception ex) {
// WTF else am I supposed to do with this exception?
throw new RuntimeException(ex);
}
}
}
protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
return new ResponseHandler<StreamResponseMessage>() {
public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {
StatusLine statusLine = httpResponse.getStatusLine();
if (log.isLoggable(Level.FINE))
log.fine("Received HTTP response: " + statusLine);
// Status
UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase());
// Message
StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);
// Headers
responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));
// Body
HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
if (enreplacedy == null || enreplacedy.getContentLength() == 0)
return responseMessage;
if (responseMessage.isContentTypeMissingOrText()) {
if (log.isLoggable(Level.FINE))
log.fine("HTTP response message contains text enreplacedy");
responseMessage.setBody(UpnpMessage.BodyType.STRING, EnreplacedyUtils.toString(enreplacedy));
} else {
if (log.isLoggable(Level.FINE))
log.fine("HTTP response message contains binary enreplacedy");
responseMessage.setBody(UpnpMessage.BodyType.BYTES, EnreplacedyUtils.toByteArray(enreplacedy));
}
return responseMessage;
}
};
}
protected HttpParams getRequestParams(StreamRequestMessage requestMessage) {
HttpParams localParams = new BasicHttpParams();
localParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, requestMessage.getOperation().getHttpMinorVersion() == 0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1);
// DefaultHttpClient adds HOST header automatically in its default processor
// Add the default user agent if not already set on the message
if (!requestMessage.getHeaders().containsKey(UpnpHeader.Type.USER_AGENT)) {
HttpProtocolParams.setUserAgent(localParams, getConfiguration().getUserAgentValue(requestMessage.getUdaMajorVersion(), requestMessage.getUdaMinorVersion()));
}
return new DefaultedHttpParams(localParams, globalParams);
}
}
18
Source : RestService.java
with Apache License 2.0
from Kyligence
with Apache License 2.0
from Kyligence
private HttpClient getHttpClient(int connectionTimeout, int readTimeout) {
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
return new DefaultHttpClient(httpParams);
}
18
Source : LazySchemeSocketFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
/**
* @param socket {@link Socket}
* @param target
* @param port
* @param params {@link HttpParams}
* @return the socket
*/
@Override
public Socket createLayeredSocket(Socket socket, String target, int port, HttpParams params) throws IOException, UnknownHostException {
return AdapteeHolder.getINSTANCE().createLayeredSocket(socket, target, port, params);
}
18
Source : LazySchemeSocketFactory.java
with Apache License 2.0
from johrstrom
with Apache License 2.0
from johrstrom
/**
* @param sock
* @param remoteAddress
* @param localAddress
* @param params
* @return the socket
* @throws IOException
* @throws UnknownHostException
* @throws ConnectTimeoutException
* @see org.apache.http.conn.scheme.SchemeSocketFactory#connectSocket(java.net.Socket, java.net.InetSocketAddress, java.net.InetSocketAddress, org.apache.http.params.HttpParams)
*/
@Override
public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
return AdapteeHolder.getINSTANCE().connectSocket(sock, remoteAddress, localAddress, params);
}
18
Source : ImageUpload.java
with MIT License
from hubcarl
with MIT License
from hubcarl
public static void upload(String path) {
HttpParams params = new BasicHttpParams();
params.setParameter("image", bitmapToString(path));
new HttpAsyncClient(UPLOAD_IMAGE_URL, params, new HttpResponseCallback() {
@Override
public void onSuccess(String response) {
}
@Override
public void onError(String response) {
Log.e(">>>loadOnlineMusic onError:", response);
}
}).execute();
}
18
Source : HttpclientConnectionManager.java
with MIT License
from dromara
with MIT License
from dromara
/**
* @author gongjun[[email protected]]
* @since 2017-04-20 17:23
*/
public clreplaced HttpclientConnectionManager implements ForestConnectionManager {
private HttpParams httpParams;
private static PoolingHttpClientConnectionManager tsConnectionManager;
private static PoolingNHttpClientConnectionManager asyncConnectionManager;
private static Lookup<AuthSchemeProvider> authSchemeRegistry;
private final ForestSSLConnectionFactory sslConnectFactory = new ForestSSLConnectionFactory();
public HttpclientConnectionManager() {
}
@Override
public void init(ForestConfiguration configuration) {
try {
httpParams = new BasicHttpParams();
Integer maxConnections = configuration.getMaxConnections() != null ? configuration.getMaxConnections() : HttpConnectionConstants.DEFAULT_MAX_TOTAL_CONNECTIONS;
Integer maxRouteConnections = configuration.getMaxRouteConnections() != null ? configuration.getMaxRouteConnections() : HttpConnectionConstants.DEFAULT_MAX_TOTAL_CONNECTIONS;
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectFactory).register("http", new PlainConnectionSocketFactory()).build();
tsConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
tsConnectionManager.setMaxTotal(maxConnections);
tsConnectionManager.setDefaultMaxPerRoute(maxRouteConnections);
// / init async connection manager
boolean supportAsync = true;
try {
Clreplaced.forName("org.apache.http.nio.client.HttpAsyncClient");
} catch (ClreplacedNotFoundException e) {
supportAsync = false;
}
if (supportAsync) {
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
if (asyncConnectionManager == null) {
try {
ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).register(AuthSchemes.DIGEST, new DigestSchemeFactory()).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
asyncConnectionManager = new PoolingNHttpClientConnectionManager(ioReactor);
asyncConnectionManager.setMaxTotal(maxConnections);
asyncConnectionManager.setDefaultMaxPerRoute(maxRouteConnections);
asyncConnectionManager.setDefaultConnectionConfig(connectionConfig);
} catch (Throwable t) {
}
}
}
} catch (Throwable th) {
throw new ForestRuntimeException(th);
}
}
public HttpClient getHttpClient(ForestRequest request, CookieStore cookieStore) {
sslConnectFactory.setCurrentRequest(request);
HttpClientBuilder builder = HttpClients.custom();
builder.setConnectionManager(tsConnectionManager);
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(request.getTimeout());
// 设置读取超时
Integer timeout = request.getTimeout();
if (timeout == null) {
timeout = request.getConfiguration().getTimeout();
}
configBuilder.setSocketTimeout(timeout);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(HttpConnectionConstants.DEFAULT_READ_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
// 设置Cookie策略
configBuilder.setCookieSpec(CookieSpecs.STANDARD);
RequestConfig requestConfig = configBuilder.build();
ForestProxy forestProxy = request.getProxy();
if (forestProxy != null) {
HttpHost proxy = new HttpHost(forestProxy.getHost(), forestProxy.getPort());
if (StringUtils.isNotEmpty(forestProxy.getUsername()) && StringUtils.isNotEmpty(forestProxy.getPreplacedword())) {
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(proxy), new UsernamePreplacedwordCredentials(forestProxy.getUsername(), forestProxy.getPreplacedword()));
builder.setDefaultCredentialsProvider(provider);
}
configBuilder.setProxy(proxy);
}
if (cookieStore != null) {
builder.setDefaultCookieStore(cookieStore);
}
HttpClient httpClient = builder.setDefaultRequestConfig(requestConfig).build();
return httpClient;
}
public void afterConnect() {
sslConnectFactory.removeCurrentRequest();
}
public CloseableHttpAsyncClient getHttpAsyncClient(ForestRequest request) {
if (asyncConnectionManager == null) {
throw new ForestUnsupportException("Async forest request is unsupported.");
}
HttpAsyncClientBuilder builder = HttpAsyncClients.custom();
Integer timeout = request.getTimeout();
if (timeout == null) {
timeout = request.getConfiguration().getTimeout();
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(HttpConnectionConstants.DEFAULT_READ_TIMEOUT).build();
return builder.setConnectionManager(asyncConnectionManager).setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultRequestConfig(requestConfig).build();
}
}
18
Source : QSystemHtmlInstance.java
with GNU General Public License v3.0
from bcgov
with GNU General Public License v3.0
from bcgov
/**
* @author Evgeniy Egorov
*/
public clreplaced QSystemHtmlInstance {
private static final QSystemHtmlInstance HTML_INSTANCE = new QSystemHtmlInstance();
private final HttpParams params = new BasicHttpParams();
private final HttpService httpService;
private QSystemHtmlInstance() {
this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, "QSystemReportHttpServer/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpQSystemReportsHandler());
// Set up the HTTP service
this.httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params);
}
public static QSystemHtmlInstance htmlInstance() {
return HTML_INSTANCE;
}
public HttpService getHttpService() {
return httpService;
}
public HttpParams getParams() {
return params;
}
}
18
Source : SyncHttpClient.java
with Apache License 2.0
from 13120241790
with Apache License 2.0
from 13120241790
/**
* Sets maximum limit of parallel connections
*
* @param maxConnections maximum parallel connections, must be at least 1
*/
public void setMaxConnections(int maxConnections) {
if (maxConnections < 1)
maxConnections = DEFAULT_MAX_CONNECTIONS;
this.maxConnections = maxConnections;
final HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(this.maxConnections));
}
18
Source : SyncHttpClient.java
with Apache License 2.0
from 13120241790
with Apache License 2.0
from 13120241790
/**
* Sets the Proxy by it's hostname and port
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
*/
public void setProxy(String hostname, int port) {
final HttpHost proxy = new HttpHost(hostname, port);
final HttpParams httpParams = this.httpClient.getParams();
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
17
Source : HttpResponseWrapper.java
with Educational Community License v2.0
from opencast
with Educational Community License v2.0
from opencast
@Override
public void setParams(HttpParams httpParams) {
response.setParams(httpParams);
}
17
Source : LivyRestClient.java
with Apache License 2.0
from Kyligence
with Apache License 2.0
from Kyligence
private void init() {
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
cm.setMaxTotal(config.getRestClientMaxTotal());
baseUrl = config.getLivyUrl();
client = new DefaultHttpClient(cm, httpParams);
}
17
Source : HttpEngine.java
with Apache License 2.0
from JackChan1999
with Apache License 2.0
from JackChan1999
public DefaultHttpClient createHttpClient() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = createHttpParams();
return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
}
17
Source : HttpRequest.java
with Apache License 2.0
from coderJohnZhang
with Apache License 2.0
from coderJohnZhang
/**
* 发送一个GET请求
*
* @return
* @throws Exception
*/
private HttpRequest get() throws Exception {
HttpGet httpget = null;
String result = null;
int respCode = -1;
try {
httpget = new HttpGet(reqUrl);
httpget.setHeader("Connection", "close");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 1000 * 60);
httpget.setParams(params);
HttpResponse response = new DefaultHttpClient().execute(httpget);
result = EnreplacedyUtils.toString(response.getEnreplacedy(), charset).trim();
respCode = response.getStatusLine().getStatusCode();
if (respCode == HttpStatus.SC_OK) {
this.respResult = result;
}
} catch (Exception e) {
throw e;
} finally {
if (null != httpget) {
httpget = null;
}
}
return this;
}
17
Source : SyncHttpClient.java
with Apache License 2.0
from 13120241790
with Apache License 2.0
from 13120241790
/**
* Sets the Proxy by it's hostname,port,username and preplacedword
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param username the username
* @param preplacedword the preplacedword
*/
public void setProxy(String hostname, int port, String username, String preplacedword) {
httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), new UsernamePreplacedwordCredentials(username, preplacedword));
final HttpHost proxy = new HttpHost(hostname, port);
final HttpParams httpParams = this.httpClient.getParams();
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
16
Source : MyHttpClient.java
with Apache License 2.0
from SwiftyWang
with Apache License 2.0
from SwiftyWang
public clreplaced MyHttpClient {
private DefaultHttpClient httpClient;
private HttpPost httpPost;
private HttpGet httpGet;
private HttpEnreplacedy httpEnreplacedy;
private HttpResponse httpResponse;
private int timeoutConnection = 6000;
private HttpParams httpParameters;
private int timeoutSocket = 6000;
public MyHttpClient() {
// Set the timeout in
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, // Set the default socket timeout
timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
}
public MyHttpClient(int timeoutconn, int timeoutsock) {
// Set the timeout in
httpParameters = new BasicHttpParams();
// Set
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutconn);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutsock);
}
public String executePostRequest(String path, List<NameValuePair> params) {
httpClient = new DefaultHttpClient(httpParameters);
String ret = null;
try {
httpPost = new HttpPost(path);
httpEnreplacedy = new UrlEncodedFormEnreplacedy(params, HTTP.UTF_8);
addHeader(httpPost);
httpPost.setEnreplacedy(httpEnreplacedy);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
ret = EnreplacedyUtils.toString(enreplacedy);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
private void addHeader(HttpRequestBase httprequest) {
try {
httprequest.setHeader("token", MyApplication.userToken);
} catch (Exception e) {
L.e(e.toString());
}
}
public String executePostRequest(String path) throws Exception {
httpClient = new DefaultHttpClient(httpParameters);
String ret = null;
this.httpPost = new HttpPost(path);
addHeader(httpPost);
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
ret = EnreplacedyUtils.toString(enreplacedy);
}
return ret;
}
public String executeGetRequest(String path) throws Exception {
path = path.replace(" ", "%20");
httpClient = new DefaultHttpClient(httpParameters);
String ret = null;
httpGet = new HttpGet(path);
addHeader(httpGet);
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
ret = EnreplacedyUtils.toString(enreplacedy);
}
return ret;
}
}
16
Source : AbstractGoogleClientFactory.java
with Eclipse Public License 1.0
from sonatype-nexus-community
with Eclipse Public License 1.0
from sonatype-nexus-community
/**
* Replicates default connection and protocol parameters used within
* {@link ApacheHttpTransport#newDefaultHttpClient()} with one exception:
*
* Stale checking is enabled.
*/
HttpParams newDefaultHttpParams() {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setStaleCheckingEnabled(params, true);
HttpConnectionParams.setSocketBufferSize(params, 8192);
ConnManagerParams.setMaxTotalConnections(params, 200);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(200));
return params;
}
16
Source : ThreadPoolHttpClient.java
with MIT License
from pospospos2007
with MIT License
from pospospos2007
public void test() throws Exception {
exe = Executors.newFixedThreadPool(POOL_SIZE);
HttpParams params = new BasicHttpParams();
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
// ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(10);
final HttpClient httpClient = new DefaultHttpClient(cm, params);
// URIs to perform GETs on
final String[] urisToGet = urls;
/* 有多少url创建多少线程,url多时机子撑不住
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads,等待所有请求完成
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
使用线程池*/
for (int i = 0; i < urisToGet.length; i++) {
final int j = i;
System.out.println(j);
HttpGet httpget = new HttpGet(urisToGet[i]);
exe.execute(new GetThread(httpClient, httpget));
}
// 创建线程池,每次调用POOL_SIZE
/*
for (int i = 0; i < urisToGet.length; i++) {
final int j=i;
System.out.println(j);
exe.execute(new Thread() {
@Override
public void run() {
this.setName("threadsPoolClient"+j);
try {
this.sleep(100);
System.out.println(j);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpGet httpget = new HttpGet(urisToGet[j]);
new GetThread(httpClient, httpget).get();
}
});
}
*/
// exe.shutdown();
System.out.println("Done");
}
16
Source : ProxyingHttpClient.java
with Apache License 2.0
from ngageoint
with Apache License 2.0
from ngageoint
/**
* Attempts to configure the proxy to the given URI in the HTTP parameters.
*
* @param params the HTTP parameters in which the proxy configuration will
* be stored.
* @param uri the requested URI.
* @throws IOException if an error occurs while determining the proxy
* server.
*/
protected void configureProxy(final HttpParams params, final URI uri) throws IOException {
try {
configureProxy(params, uri.toURL());
} catch (final MalformedURLException e) {
LOGGER.warn("The URI '" + uri + "' could not be converted to a URL. The proxy will not be configured.", e);
}
}
16
Source : HttpServerConnectionUpnpStream.java
with GNU General Public License v2.0
from newPersonKing
with GNU General Public License v2.0
from newPersonKing
/**
* Implementation for Apache HTTP Components API.
*
* @author Christian Bauer
*/
public abstract clreplaced HttpServerConnectionUpnpStream extends UpnpStream {
final private static Logger log = Logger.getLogger(UpnpStream.clreplaced.getName());
protected final HttpServerConnection connection;
protected final BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
protected final HttpService httpService;
protected final HttpParams params;
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory, HttpServerConnection connection, final HttpParams params) {
super(protocolFactory);
this.connection = connection;
this.params = params;
// The Date header is recommended in UDA, need to doreplacedent the requirement in StreamServer interface?
httpProcessor.addInterceptor(new ResponseDate());
// The Server header is only required for Control so callers have to add it to UPnPMessage
// httpProcessor.addInterceptor(new ResponseServer());
httpProcessor.addInterceptor(new ResponseContent());
httpProcessor.addInterceptor(new ResponseConnControl());
httpService = new UpnpHttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
httpService.setParams(params);
}
public HttpServerConnection getConnection() {
return connection;
}
public void run() {
try {
while (!Thread.interrupted() && connection.isOpen()) {
log.fine("Handling request on open connection...");
HttpContext context = new BasicHttpContext(null);
httpService.handleRequest(connection, context);
}
} catch (ConnectionClosedException ex) {
log.fine("Client closed connection");
responseException(ex);
} catch (SocketTimeoutException ex) {
log.fine("Server-side closed socket (this is 'normal' behavior of Apache HTTP Core!): " + ex.getMessage());
} catch (IOException ex) {
log.warning("I/O exception during HTTP request processing: " + ex.getMessage());
responseException(ex);
} catch (HttpException ex) {
throw new UnsupportedDataException("Request malformed: " + ex.getMessage(), ex);
} finally {
try {
connection.shutdown();
} catch (IOException ex) {
log.fine("Error closing connection: " + ex.getMessage());
}
}
}
/**
* A thread-safe custom service implementation that creates a UPnP message from the request,
* then preplacedes it to <tt>UpnpStream#process()</tt>, finally sends the response back to the
* client.
*/
protected clreplaced UpnpHttpService extends HttpService {
public UpnpHttpService(HttpProcessor processor, ConnectionReuseStrategy reuse, HttpResponseFactory responseFactory) {
super(processor, reuse, responseFactory);
}
@Override
protected void doService(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext ctx) throws HttpException, IOException {
log.fine("Processing HTTP request: " + httpRequest.getRequestLine().toString());
// Extract what we need from the HTTP httpRequest
String requestMethod = httpRequest.getRequestLine().getMethod();
String requestURI = httpRequest.getRequestLine().getUri();
StreamRequestMessage requestMessage;
try {
requestMessage = new StreamRequestMessage(UpnpRequest.Method.getByHttpName(requestMethod), URI.create(requestURI));
} catch (IllegalArgumentException e) {
String msg = "Invalid request URI: " + requestURI + ": " + e.getMessage();
log.warning(msg);
throw new HttpException(msg, e);
}
if (requestMessage.getOperation().getMethod().equals(UpnpRequest.Method.UNKNOWN)) {
log.fine("Method not supported by UPnP stack: " + requestMethod);
throw new MethodNotSupportedException("Method not supported: " + requestMethod);
}
log.fine("Created new request message: " + requestMessage);
// HTTP version
int requestHttpMinorVersion = httpRequest.getProtocolVersion().getMinor();
requestMessage.getOperation().setHttpMinorVersion(requestHttpMinorVersion);
// Connection wrapper
requestMessage.setConnection(createConnection());
// Headers
requestMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpRequest)));
// Body
if (httpRequest instanceof HttpEnreplacedyEnclosingRequest) {
log.fine("Request contains enreplacedy body, setting on UPnP message");
HttpEnreplacedyEnclosingRequest enreplacedyEnclosingHttpRequest = (HttpEnreplacedyEnclosingRequest) httpRequest;
HttpEnreplacedy enreplacedy = enreplacedyEnclosingHttpRequest.getEnreplacedy();
if (requestMessage.isContentTypeMissingOrText()) {
log.fine("HTTP request message contains text enreplacedy");
requestMessage.setBody(UpnpMessage.BodyType.STRING, EnreplacedyUtils.toString(enreplacedy));
} else {
log.fine("HTTP request message contains binary enreplacedy");
requestMessage.setBody(UpnpMessage.BodyType.BYTES, EnreplacedyUtils.toByteArray(enreplacedy));
}
} else {
log.fine("Request did not contain enreplacedy body");
}
// Finally process it
StreamResponseMessage responseMsg;
try {
responseMsg = process(requestMessage);
} catch (RuntimeException ex) {
log.fine("Exception occurred during UPnP stream processing: " + ex);
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Cause: " + Exceptions.unwrap(ex), Exceptions.unwrap(ex));
}
log.fine("Sending HTTP response: " + HttpStatus.SC_INTERNAL_SERVER_ERROR);
httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
responseException(ex);
return;
}
if (responseMsg != null) {
log.fine("Sending HTTP response message: " + responseMsg);
// Status line
httpResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("HTTP", 1, responseMsg.getOperation().getHttpMinorVersion()), responseMsg.getOperation().getStatusCode(), responseMsg.getOperation().getStatusMessage()));
log.fine("Response status line: " + httpResponse.getStatusLine());
// Headers
httpResponse.setParams(getResponseParams(requestMessage.getOperation()));
HeaderUtil.add(httpResponse, responseMsg.getHeaders());
// Enreplacedy
if (responseMsg.hasBody() && responseMsg.getBodyType().equals(UpnpMessage.BodyType.BYTES)) {
httpResponse.setEnreplacedy(new ByteArrayEnreplacedy(responseMsg.getBodyBytes()));
} else if (responseMsg.hasBody() && responseMsg.getBodyType().equals(UpnpMessage.BodyType.STRING)) {
StringEnreplacedy responseEnreplacedy = new StringEnreplacedy(responseMsg.getBodyString(), "UTF-8");
httpResponse.setEnreplacedy(responseEnreplacedy);
}
} else {
// If it's null, it's 404, everything else needs a proper httpResponse
log.fine("Sending HTTP response: " + HttpStatus.SC_NOT_FOUND);
httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND);
}
responseSent(responseMsg);
}
protected HttpParams getResponseParams(UpnpOperation operation) {
HttpParams localParams = new BasicHttpParams();
return new DefaultedHttpParams(localParams, params);
}
}
abstract protected Connection createConnection();
}
16
Source : HttpClientFactory.java
with GNU General Public License v3.0
from liaozhoubei
with GNU General Public License v3.0
from liaozhoubei
public static DefaultHttpClient create(boolean isHttps) {
HttpParams params = createHttpParams();
DefaultHttpClient httpClient = null;
if (isHttps) {
// 支持http与https
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// ThreadSafeClientConnManager线程安全管理类
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient = new DefaultHttpClient(cm, params);
} else {
httpClient = new DefaultHttpClient(params);
}
return httpClient;
}
16
Source : AsyncHttpClient.java
with Apache License 2.0
from JackChan1999
with Apache License 2.0
from JackChan1999
public void setTimeout(int timeout) {
HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setTimeout(httpParams, (long) timeout);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
}
16
Source : HttpResponseProxy.java
with Apache License 2.0
from IBM
with Apache License 2.0
from IBM
@Override
@Deprecated
public void setParams(final HttpParams params) {
original.setParams(params);
}
16
Source : HttpSyncClient.java
with MIT License
from hubcarl
with MIT License
from hubcarl
public static String httpPost(String url, HttpParams params) {
HttpPost httpRequest = new HttpPost(url);
if (params != null) {
httpRequest.setParams(params);
}
try {
// 取得HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
// 请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// 请求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
return EnreplacedyUtils.toString(httpResponse.getEnreplacedy());
} else {
Log.e(">>>httpPost httpResponse", httpResponse.getStatusLine().getStatusCode() + "");
return Strings.EMPTY_STRING;
}
} catch (ClientProtocolException e) {
Log.e(">>>httpPost ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e(">>>httpPost IOException", e.toString());
}
return Strings.EMPTY_STRING;
}
16
Source : TestHttpServer.java
with Apache License 2.0
from firebase
with Apache License 2.0
from firebase
public clreplaced TestHttpServer {
private final HttpParams params;
private final BasicHttpProcessor httpproc;
private final ConnectionReuseStrategy connStrategy;
private final HttpResponseFactory responseFactory;
private final HttpRequestHandlerRegistry reqistry;
private final ServerSocket serversocket;
private HttpExpectationVerifier expectationVerifier;
private Thread listener;
private volatile boolean shutdown;
public TestHttpServer(ServerSocketFactory socketFactory, int port) throws IOException {
super();
this.params = new BasicHttpParams();
this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024).setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.httpproc = new BasicHttpProcessor();
this.httpproc.addInterceptor(new ResponseDate());
this.httpproc.addInterceptor(new ResponseServer());
this.httpproc.addInterceptor(new ResponseContent());
this.httpproc.addInterceptor(new ResponseConnControl());
this.connStrategy = new DefaultConnectionReuseStrategy();
this.responseFactory = new DefaultHttpResponseFactory();
this.reqistry = new HttpRequestHandlerRegistry();
this.serversocket = socketFactory.createServerSocket(port);
}
public TestHttpServer(int port) throws IOException {
this(ServerSocketFactory.getDefault(), port);
}
public TestHttpServer() throws IOException {
this(0);
}
public void registerHandler(final String pattern, final HttpRequestHandler handler) {
this.reqistry.register(pattern, handler);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
private HttpServerConnection acceptConnection() throws IOException {
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
return conn;
}
public int getPort() {
return this.serversocket.getLocalPort();
}
public InetAddress getInetAddress() {
return this.serversocket.getInetAddress();
}
public void start() {
if (this.listener != null) {
throw new IllegalStateException("Listener already running");
}
this.listener = new Thread(new Runnable() {
public void run() {
while (!shutdown && !Thread.interrupted()) {
try {
// Set up HTTP connection
HttpServerConnection conn = acceptConnection();
// Set up the HTTP service
HttpService httpService = new HttpService(httpproc, connStrategy, responseFactory);
httpService.setParams(params);
httpService.setExpectationVerifier(expectationVerifier);
httpService.setHandlerResolver(reqistry);
// Start worker thread
Thread t = new WorkerThread(httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
break;
}
}
}
});
this.listener.start();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ignore) {
}
if (listener != null) {
this.listener.interrupt();
try {
this.listener.join(1000);
} catch (InterruptedException ignore) {
}
}
}
static clreplaced WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(final HttpService httpservice, final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
16
Source : HttpRequest.java
with Apache License 2.0
from coderJohnZhang
with Apache License 2.0
from coderJohnZhang
/**
* 获取文件流
*
* @return
*/
public InputStream getInputStream() {
InputStream in = null;
HttpGet httpget = null;
int respCode = -1;
try {
httpget = new HttpGet(reqUrl);
httpget.setHeader("Connection", "close");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 1000 * 60);
httpget.setParams(params);
HttpResponse response = new DefaultHttpClient().execute(httpget);
respCode = response.getStatusLine().getStatusCode();
if (respCode == HttpStatus.SC_OK) {
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
in = enreplacedy.getContent();
}
fileTotalLength = response.getEnreplacedy().getContentLength();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpget) {
httpget = null;
}
}
return in;
}
16
Source : FakeSocketFactory.java
with GNU General Public License v2.0
from Cloudslab
with GNU General Public License v2.0
from Cloudslab
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
SSLSocket sslsock = sock != null ? sock : createSocket();
if (localAddress != null || localPort > 0) {
if (localPort < 0) {
localPort = 0;
}
sslsock.bind(new InetSocketAddress(localAddress, localPort));
}
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
16
Source : SyncHttpClient.java
with Apache License 2.0
from 13120241790
with Apache License 2.0
from 13120241790
/**
* Set the connection and socket timeout. By default, 10 seconds.
*
* @param timeout the connect/socket timeout in milliseconds, at least 1 second
*/
public void setTimeout(int timeout) {
if (timeout < 1000)
timeout = DEFAULT_SOCKET_TIMEOUT;
this.timeout = timeout;
final HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setTimeout(httpParams, this.timeout);
HttpConnectionParams.setSoTimeout(httpParams, this.timeout);
HttpConnectionParams.setConnectionTimeout(httpParams, this.timeout);
}
15
Source : SOAPClient.java
with Apache License 2.0
from wso2
with Apache License 2.0
from wso2
/**
* Sets up the client
*/
private void setup() {
httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
return false;
}
});
}
15
Source : OkApacheClientStack.java
with MIT License
from why168
with MIT License
from why168
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
}
15
Source : SSLSocketFactory.java
with GNU General Public License v3.0
from ultrasonic
with GNU General Public License v3.0
from ultrasonic
/**
* @deprecated Use {@link #connectSocket(Socket, InetSocketAddress, InetSocketAddress, HttpParams)}
*/
@Deprecated
public Socket connectSocket(final Socket socket, final String host, int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {
InetSocketAddress local = null;
if (localAddress != null || localPort > 0) {
// we need to bind explicitly
if (localPort < 0) {
// indicates "any"
localPort = 0;
}
local = new InetSocketAddress(localAddress, localPort);
}
InetAddress remoteAddress;
if (this.nameResolver != null) {
remoteAddress = this.nameResolver.resolve(host);
} else {
remoteAddress = InetAddress.getByName(host);
}
InetSocketAddress remote = new InetSocketAddress(remoteAddress, port);
return connectSocket(socket, remote, local, params);
}
15
Source : SyncHttp.java
with Apache License 2.0
from u014427391
with Apache License 2.0
from u014427391
/**
* 通过GET方式发送请求
* @param url URL地址
* @param params 参数
* @return
* @throws Exception
*/
public String httpGet(String url, String params) throws Exception {
// 返回信息
String response = null;
// 拼接请求URL
if (null != params && !params.equals("")) {
url += "?" + params;
}
int timeoutConnection = 3000;
int timeoutSocket = 5000;
// Set the timeout in milliseconds until a connection is established.
HttpParams httpParameters = new BasicHttpParams();
// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 构造HttpClient的实例
HttpClient httpClient = new DefaultHttpClient(httpParameters);
// 创建GET方法的实例
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (// SC_OK = 200
statusCode == HttpStatus.SC_OK) {
// 获得返回结果
response = EnreplacedyUtils.toString(httpResponse.getEnreplacedy());
} else {
response = "返回码:" + statusCode;
}
} catch (Exception e) {
throw new Exception(e);
}
return response;
}
15
Source : WebService.java
with GNU Affero General Public License v3.0
from RooyeKhat-Media
with GNU Affero General Public License v3.0
from RooyeKhat-Media
private static String callWebService(String method, List nameValuePairs) {
try {
HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 10000);
HttpConnectionParams.setSoTimeout(my_httpParams, 5000);
org.apache.http.client.HttpClient client = new org.apache.http.impl.client.DefaultHttpClient(my_httpParams);
HttpPost post = new HttpPost(url + method);
String apikey = ApiControl.encryption(ApiControl.apiKey);
nameValuePairs.add(new BasicNameValuePair("key", apikey));
post.setEnreplacedy(new UrlEncodedFormEnreplacedy(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
int resCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEnreplacedy().getContent()));
String line;
String ret = null;
if (resCode == 200) {
ret = "";
while ((line = rd.readLine()) != null) {
ret = ret + line;
}
return ret;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
15
Source : AVRHTTPClient.java
with GNU General Public License v3.0
from pskiwi
with GNU General Public License v3.0
from pskiwi
// Workaround für OOM
// http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
public static void configureHTTPClient(DefaultHttpClient httpclient) {
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 5000;
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 4000;
// set timeout parameters for HttpClient
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// setting
HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
// setSocketBufferSize
httpclient.setParams(httpParameters);
}
15
Source : HttpAuthenticationMechanismDBTest.java
with Eclipse Public License 1.0
from OpenLiberty
with Eclipse Public License 1.0
from OpenLiberty
@Before
public void setupConnection() {
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
httpclient = new DefaultHttpClient(httpParams);
}
15
Source : DatabaseIdentityStoreImmediateSettingsTest.java
with Eclipse Public License 1.0
from OpenLiberty
with Eclipse Public License 1.0
from OpenLiberty
@Before
public void setupConnection() {
// disable auto redirect.
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
httpclient = new DefaultHttpClient(httpParams);
}
See More Examples