private HttpClient newHttpClient(String sslProtocol, HttpRequest request) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, httpTimeoutsProvider.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(params, httpTimeoutsProvider.getSocketTimeout()); // AG-1059: Need to follow redirects to ensure that if the host app is setup with Apache and // mod_jk we can still // fetch internal gadgets. if (request.getFollowRedirects()) { params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); params.setIntParameter(ClientPNames.MAX_REDIRECTS, 3); } params.setParameter( ClientPNames.DEFAULT_HEADERS, ImmutableSet.of(new BasicHeader("Accept-Encoding", "gzip, deflate"))); DefaultHttpClient client = new DefaultHttpClient(params); // AG-1044: Need to use the JVM's default proxy configuration for requests. ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); client.addResponseInterceptor(new GzipDeflatingInterceptor()); client .getConnectionManager() .getSchemeRegistry() .register(new Scheme("https", new CustomSSLSocketFactory(sslProtocol), 443)); return client; }
/** * 获取HttpClient,不同的业务场景传入不同的连接超时、请求超时参数 * * @param url 访问的url * @param timeOut 连接超时 * @param soTimeout 请求超时 * @return HttpClient */ public static HttpClient getHttpClient(String url, int timeOut, int soTimeout) { if (timeOut == 0) { timeOut = CONN_TIME_OUT; } if (soTimeout == 0) { soTimeout = SO_TIME_OUT; } StringBuilder sb = new StringBuilder(5); sb.append(url).append(".").append(timeOut).append(".").append(soTimeout); String key = sb.toString(); HttpClient httpclient = httpClientMap.get(key); if (httpclient == null) { httpclient = new DefaultHttpClient(connectionManager); HttpParams params = httpclient.getParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); HttpClient tempClient = httpClientMap.putIfAbsent(key, httpclient); if (tempClient != null) { httpclient = tempClient; } } return httpclient; }
/** * Creates an HttpClient with the specified userAgent string. * * @param userAgent the userAgent string * @return the client */ public static HttpClient newHttpClient(String userAgent) { // AndroidHttpClient is available on all platform releases, // but is hidden until API Level 8 try { Class<?> clazz = Class.forName("android.net.http.AndroidHttpClient"); Method newInstance = clazz.getMethod("newInstance", String.class); Object instance = newInstance.invoke(null, userAgent); HttpClient client = (HttpClient) instance; // ensure we default to HTTP 1.1 HttpParams params = client.getParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // AndroidHttpClient sets these two parameters thusly by default: // HttpConnectionParams.setSoTimeout(params, 60 * 1000); // HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); // however it doesn't set this one... ConnManagerParams.setTimeout(params, 60 * 1000); return client; } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
@Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); ClientConnectionManager connManager = null; HttpParams params = getParams(); ClientConnectionManagerFactory factory = null; String className = (String) params.getParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME); if (className != null) { try { Class<?> clazz = Class.forName(className); factory = (ClientConnectionManagerFactory) clazz.newInstance(); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Invalid class name: " + className); } catch (IllegalAccessException ex) { throw new IllegalAccessError(ex.getMessage()); } catch (InstantiationException ex) { throw new InstantiationError(ex.getMessage()); } } if (factory != null) { connManager = factory.newInstance(params, registry); } else { connManager = new SingleClientConnManager(registry); } return connManager; }
protected @Nonnull HttpClient getClient(String url, boolean multipart) throws InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new InternalException("No context was specified for this request"); } boolean ssl = url.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); if (!multipart) { HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); } HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter( ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
public String call(String url, Map<String, String> fields) { // create an HTTP request to a protected resource HttpGet request = new HttpGet(endpoint); HttpParams p = new BasicHttpParams(); for (Entry<String, String> en : fields.entrySet()) { p.setParameter(en.getKey(), en.getValue()); } request.setParams(p); // sign the request try { consumer2.sign(request); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } // send the request HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); return convertStreamToString(response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public void loginUGotFile() throws Exception { loginsuccessful = false; HttpParams params = new BasicHttpParams(); params.setParameter( "http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to ugotfile.com"); HttpPost httppost = new HttpPost("http://ugotfile.com/user/login"); httppost.setHeader("Cookie", phpsessioncookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("ugfLoginUserName", getUsername())); formparams.add(new BasicNameValuePair("ugfLoginPassword", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); if (httpresponse.getStatusLine().toString().contains("302")) { tmp = httpresponse.getLastHeader("Location").getValue(); NULogger.getLogger().info("UGotFile Login success"); loginsuccessful = true; username = getUsername(); password = getPassword(); } else { NULogger.getLogger().info("UGotFile login failed"); loginsuccessful = false; username = ""; password = ""; showWarningMessage(Translation.T().loginerror(), HOSTNAME); accountUIShow().setVisible(true); } }
/** * Perform an HTTP Status check and return the response code * * @return * @throws IOException */ public int getHTTPStatusCode() throws IOException { HttpClient client = new DefaultHttpClient(); BasicHttpContext localContext = new BasicHttpContext(); System.out.println("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState); if (this.mimicWebDriverCookieState) { localContext.setAttribute( ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies())); } HttpRequestBase requestMethod = this.httpRequestMethod.getRequestMethod(); requestMethod.setURI(this.linkToCheck); HttpParams httpRequestParameters = requestMethod.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects); requestMethod.setParams(httpRequestParameters); System.out.println( "Sending " + requestMethod.getMethod() + " request for: " + requestMethod.getURI()); HttpResponse response = client.execute(requestMethod, localContext); System.out.println( "HTTP " + requestMethod.getMethod() + " request status: " + response.getStatusLine().getStatusCode()); return response.getStatusLine().getStatusCode(); }
public org.apache.http.client.HttpClient configureClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setUseExpectContinue(params, useExpectContinue); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); HttpConnectionParams.setTcpNoDelay(params, Boolean.TRUE); String protocol = "http"; if (enableSSL) protocol = "https"; params.setParameter(ClientPNames.DEFAULT_HOST, new HttpHost(host, port, protocol)); if (proxy != null) { params.setParameter( ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy, proxyPort, protocol)); } DefaultHttpClient client = new DefaultHttpClient(configureConnectionManager(params), params); if (username != null && password != null) { client .getCredentialsProvider() .setCredentials( new AuthScope(host, port, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0); } return client; }
static { httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); // set the time out of the connection/ socket. and the cache size HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // set the connection manager factory params.setParameter( ClientPNames.CONNECTION_MANAGER_FACTORY, new ClientConnectionManagerFactory() { public ClientConnectionManager newInstance( HttpParams params, SchemeRegistry schemeRegistry) { return new ThreadSafeClientConnManager(params, schemeRegistry); } }); // set the redirect, default is true HttpClientParams.setRedirecting(params, true); // set the client verion HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // set user-agent HttpProtocolParams.setUserAgent(params, "eoeWIKI_Android/0.9"); // set the charset HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // set not activate Expect:100-Continue HttpProtocolParams.setUseExpectContinue(params, false); // set the version of the cookie params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965); }
protected DefaultHttpClient getHttpClient() { if (httpClient == null) { HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8); HttpProtocolParams.setUseExpectContinue( httpParams, false); // some webservers have problems if this is set to true ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS); HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT); // httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new // HttpHost("192.168.16.180", 8888, "http")); httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpClient = new DefaultHttpClient(connectionManager, httpParams); } return httpClient; }
public static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); try { params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); } catch (Exception e2) { // can ignore } SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
private HttpResponse getHTTPResponse() throws IOException, NullPointerException { if (fileURI == null) throw new NullPointerException("No file URI specified"); HttpClient client = new DefaultHttpClient(); BasicHttpContext localContext = new BasicHttpContext(); // Clear down the local cookie store every time to make sure we don't have any left over cookies // influencing the test localContext.setAttribute(ClientContext.COOKIE_STORE, null); LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState); if (mimicWebDriverCookieState) { localContext.setAttribute( ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies())); } HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod(); requestMethod.setURI(fileURI); HttpParams httpRequestParameters = requestMethod.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); requestMethod.setParams(httpRequestParameters); // TODO if post send map of variables, also need to add a post map setter LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI); return client.execute(requestMethod, localContext); }
public HttpClient4Sender() { clientParams.setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS); clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_READ_TIMEOUT_MILLISECONDS); HttpProtocolParams.setVersion(clientParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(clientParams, "UTF-8"); }
private static HttpParams getHttpParams() { HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); return params; }
/** * Sets the Proxy by it's hostname,port,username and password * * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param username the username * @param password the password */ public void setProxy(String hostname, int port, String username, String password) { httpClient .getCredentialsProvider() .setCredentials( new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password)); final HttpHost proxy = new HttpHost(hostname, port); final HttpParams httpParams = this.httpClient.getParams(); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }
private JSONObject Get(String url) throws ClientProtocolException, IOException, IllegalStateException, JSONException { HttpGet req = new HttpGet(url); HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); req.setParams(params); HttpResponse response = client.execute(req); JSONObject result = new JSONObject(convertToString(response.getEntity().getContent())); return result; }
/** * Obtains a set of reasonable default parameters for a server. * * @return default parameters */ protected HttpParams newDefaultParams() { HttpParams params = new BasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "LocalTestServer/1.1"); return params; }
static { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, WeaveConstants.USER_AGENT); HttpProtocolParams.setUseExpectContinue(params, false); // params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); sm_httpParams = params; }
public static long getTimeout(HttpParams httpparams) { if (httpparams == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Long long1 = (Long) httpparams.getParameter("http.conn-manager.timeout"); if (long1 != null) { return long1.longValue(); } else { return (long) httpparams.getIntParameter("http.connection.timeout", 0); } }
protected HttpResponse executeRequestWithTimeout(HttpUriRequest httpReq) throws Exception { // Set timeout for the socket, connection manager // and connection itself if (httpConnectionTimeout > 0) { HttpParams httpParams = http.getParams(); httpParams.setIntParameter("http.socket.timeout", httpConnectionTimeout); httpParams.setIntParameter("http.connection-manager.timeout", httpConnectionTimeout); httpParams.setIntParameter("http.connection.timeout", httpConnectionTimeout); } return http.execute(httpReq, ctx); }
private static HttpClient getHttpClient() { HttpParams httpParameters = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); mHttpClient.getParams().setParameter("http.socket.timeout", new Integer(2000)); mHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); httpParameters.setBooleanParameter("http.protocol.expect-continue", false); return mHttpClient; }
@Before public void initServer() throws Exception { HttpParams serverParams = new SyncBasicHttpParams(); serverParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .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.server = new HttpServerNio(serverParams); this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler()); }
@Before public void initClient() throws Exception { HttpParams clientParams = new SyncBasicHttpParams(); clientParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1"); this.client = new HttpClientNio(clientParams); this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler()); }
@Override protected AbstractHttpClient createHttpClient() { AbstractHttpClient client = super.createHttpClient(); try { if (ipAddress != null) { HttpParams params = client.getParams(); params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(ipAddress)); } } catch (Exception e) { e.printStackTrace(); } return client; }
public ListenerThread(ApiServer requestHandler, int port) { try { _serverSocket = new ServerSocket(port); } catch (IOException ioex) { s_logger.error("error initializing api server", ioex); return; } _params = new BasicHttpParams(); _params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); // Set up the HTTP protocol processor BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new ResponseDate()); httpproc.addInterceptor(new ResponseServer()); httpproc.addInterceptor(new ResponseContent()); httpproc.addInterceptor(new ResponseConnControl()); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", requestHandler); // Set up the HTTP service _httpService = new HttpService( httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory()); _httpService.setParams(_params); _httpService.setHandlerResolver(reqistry); }
/* 66: */ /* 67: */ public static void setLocalAddress(HttpParams params, InetAddress local) /* 68: */ { /* 69:180 */ if (params == null) { /* 70:181 */ throw new IllegalArgumentException("Parameters must not be null."); /* 71: */ } /* 72:183 */ params.setParameter("http.route.local-address", local); /* 73: */ }
/* 47: */ /* 48: */ public static void setForcedRoute(HttpParams params, HttpRoute route) /* 49: */ { /* 50:143 */ if (params == null) { /* 51:144 */ throw new IllegalArgumentException("Parameters must not be null."); /* 52: */ } /* 53:146 */ params.setParameter("http.route.forced-route", route); /* 54: */ }
/* 27: */ /* 28: */ public static void setDefaultProxy(HttpParams params, HttpHost proxy) /* 29: */ { /* 30:101 */ if (params == null) { /* 31:102 */ throw new IllegalArgumentException("Parameters must not be null."); /* 32: */ } /* 33:104 */ params.setParameter("http.route.default-proxy", proxy); /* 34: */ }
public static int getMaxTotalConnections(HttpParams httpparams) { if (httpparams == null) { throw new IllegalArgumentException("HTTP parameters must not be null."); } else { return httpparams.getIntParameter("http.conn-manager.max-total", 20); } }