/** * Returns an array of {@link Cookie cookies} in this HTTP * state that match the given request parameters. * * @param domain the request domain * @param port the request port * @param path the request path * @param secure <code>true</code> when using HTTPS * * @return an array of {@link Cookie cookies}. * * @see #getCookies() * * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie) */ public synchronized Cookie[] getCookies( String domain, int port, String path, boolean secure ) { LOG.trace("enter HttpState.getCookies(String, int, String, boolean)"); CookieSpec matcher = CookiePolicy.getDefaultSpec(); ArrayList list = new ArrayList(cookies.size()); for (int i = 0, m = cookies.size(); i < m; i++) { Cookie cookie = (Cookie) (cookies.get(i)); if (matcher.match(domain, port, path, secure, cookie)) { list.add(cookie); } } return (Cookie[]) (list.toArray(new Cookie[list.size()])); }
private void getClient(){ CONTACT_URL = OscarProperties.getInstance().getProperty("TELEPLAN_URL",CONTACT_URL); HttpState initialState = new HttpState(); // Initial set of cookies can be retrieved from persistent storage and // re-created, using a persistence mechanism of choice, Cookie mycookie = new Cookie("moh.hnet.bc.ca","mycookie", "stuff", "/", null, false); // and then added to your HTTP state instance initialState.addCookie(mycookie); // Get HTTP client instance //HttpClientParams hcParams = new HttpClientParams(); //hcParams.setParameter("User-Agent","TeleplanPerl 1.0"); httpclient = new HttpClient(); //hcParams); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); httpclient.setState(initialState); httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); httpclient.getParams().setParameter("User-Agent","TeleplanPerl 1.0"); }
@Override public void applyTo(OwnCloudClient client) { client.getParams().setAuthenticationPreemptive(false); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setFollowRedirects(false); Uri serverUri = client.getBaseUri(); String[] cookies = mSessionCookie.split(";"); if (cookies.length > 0) { Cookie cookie = null; for (int i=0; i<cookies.length; i++) { int equalPos = cookies[i].indexOf('='); if (equalPos >= 0) { cookie = new Cookie(); cookie.setName(cookies[i].substring(0, equalPos)); cookie.setValue(cookies[i].substring(equalPos + 1)); cookie.setDomain(serverUri.getHost()); // VERY IMPORTANT cookie.setPath(serverUri.getPath()); // VERY IMPORTANT client.getState().addCookie(cookie); } } } }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } }
protected void configureHttpClient() throws IOException, GeneralSecurityException { httpClient.getParams().setAuthenticationPreemptive(isAuthenticationPreemptive()); initCredentials(); initSocketFactory(); initProtocolIfNeeded(); if (httpConnectionManager != null) { httpClient.setHttpConnectionManager(httpConnectionManager); } List<Header> headers = getDefaultHeaders(); httpClient.getHostConfiguration().getParams().setParameter(HostParams.DEFAULT_HEADERS, headers); httpClient.getParams().setParameter(HttpClientParams.USER_AGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/11.04 Chromium/18.0.1025.151 Chrome/18.0.1025.151 Safari/535.19"); httpClient.getParams().setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "UTF-8"); httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); httpClient.getParams().setConnectionManagerTimeout(connectionManagerTimeout); httpClient.getParams().setSoTimeout(soTimeout); if (connectionTimeout >= 0) { httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); } }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { // MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams() .setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
public XmlRequest(String host, int port, String protocol) { this.host = host; this.port = port; this.protocol = protocol; setMethod(Method.GET); state.addCookie(cookie); client.setState(state); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setHostConfiguration(config); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); // This will exclude the NTLM authentication scheme client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); }
/** * 获取HttpClient对象 * * @return */ private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
protected void configureDefaultHttpClientParams(HttpParams params) { params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class); params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 10000); Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>(); maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(20)); params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap); params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 20); params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000); params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2*60*1000); boolean retrySocketException = new Boolean(ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY)); if (retrySocketException) { LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler()); } }
public void testCookiePolicy2109() throws Exception { man.setCookiePolicy(CookiePolicy.RFC_2109); man.testStarted(); // ensure policy is picked up URL url = new URL("http://order.now/sub1/moo.html"); man.addCookieFromHeader("test1=moo1;", url); man.addCookieFromHeader("test2=moo2;path=/sub1", url); man.addCookieFromHeader("test2=moo3;path=/", url); assertEquals(3,man.getCookieCount()); //assertEquals("/",man.get(0).getPath()); assertEquals("/sub1",man.get(1).getPath()); assertEquals("/",man.get(2).getPath()); String s = man.getCookieHeaderForURL(url); assertNotNull(s); HC3CookieHandler hc3CookieHandler = (HC3CookieHandler) man.getCookieHandler(); org.apache.commons.httpclient.Cookie[] c = hc3CookieHandler.getCookiesForUrl(man.getCookies(), url, CookieManager.ALLOW_VARIABLE_COOKIES); assertEquals("/sub1",c[0].getPath()); assertFalse(c[0].isPathAttributeSpecified()); assertEquals("/sub1",c[1].getPath()); assertTrue(c[1].isPathAttributeSpecified()); assertEquals("/",c[2].getPath()); assertTrue(c[2].isPathAttributeSpecified()); assertEquals("$Version=0; test1=moo1; test2=moo2; $Path=/sub1; test2=moo3; $Path=/", s); }
public void testCookiePolicyNetscape() throws Exception { man.setCookiePolicy(CookiePolicy.NETSCAPE); man.testStarted(); // ensure policy is picked up URL url = new URL("http://www.order.now/sub1/moo.html"); man.addCookieFromHeader("test1=moo1;", url); man.addCookieFromHeader("test2=moo2;path=/sub1", url); man.addCookieFromHeader("test2=moo3;path=/", url); assertEquals(3,man.getCookieCount()); assertEquals("/sub1",man.get(0).getPath()); assertEquals("/sub1",man.get(1).getPath()); assertEquals("/",man.get(2).getPath()); String s = man.getCookieHeaderForURL(url); assertNotNull(s); HC3CookieHandler hc3CookieHandler = (HC3CookieHandler) man.getCookieHandler(); org.apache.commons.httpclient.Cookie[] c = hc3CookieHandler.getCookiesForUrl(man.getCookies(), url, CookieManager.ALLOW_VARIABLE_COOKIES); assertEquals("/sub1",c[0].getPath()); assertFalse(c[0].isPathAttributeSpecified()); assertEquals("/sub1",c[1].getPath()); assertTrue(c[1].isPathAttributeSpecified()); assertEquals("/",c[2].getPath()); assertTrue(c[2].isPathAttributeSpecified()); assertEquals("test1=moo1; test2=moo2; test2=moo3", s); }
public static void downloadUrl(String url, File destFile) throws IOException, HTTPException { File tmpFile = new File(destFile.getAbsoluteFile() + ".tmp"); Logger.getLogger(IOUtils.class).debug(String.format("Downloading URL %s to %s", url, tmpFile)); tmpFile.getParentFile().mkdirs(); HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); int code = client.executeMethod(get); if (code >= 200 && code < 300) { copyToFileAndCloseStreams(get.getResponseBodyAsStream(), tmpFile); tmpFile.renameTo(destFile); } else Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url); }
/** * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) * * Called upon initialization, Will create the ConfigParser and get the * RuleChain back. Will also configure the httpclient. */ public void init(FilterConfig filterConfig) throws ServletException { log = LogFactory.getLog(ProxyFilter.class); AllowedMethodHandler.setAllowedMethods("OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE"); httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false); httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); String data = filterConfig.getInitParameter("dataUrl"); if (data == null) { serverChain = null; } else { try { File dataFile = new File(filterConfig.getServletContext().getRealPath(data)); ConfigParser parser = new ConfigParser(dataFile); serverChain = parser.getServerChain(); } catch (Exception e) { throw new ServletException(e); } } }
public String login(String id) throws HttpException, IOException{ hc.getHostConfiguration().setProxy("127.0.0.1", 8087); hc.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");//������Ϣ PostMethod p = new PostMethod("http://shoufei.hebust.edu.cn/kd/login.jsp"); p.addParameter("EdtStuID", id+"';--"); p.addParameter("mm", "haha"); hc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); hc.executeMethod(p); // ��õ�½��� Cookie Cookie[] cookies = hc.getState().getCookies(); String tmpcookies = ""; for (Cookie c : cookies) { tmpcookies += c.toString() + ";"; } // ���е�½��IJ��� PostMethod postMethod = new PostMethod( "http://shoufei.hebust.edu.cn/kd/qrypayment.jsp"); // ÿ�η�������Ȩ����ַʱ�����ǰ��� cookie ��Ϊͨ��֤ postMethod.setRequestHeader("cookie", tmpcookies); hc.executeMethod(postMethod); String s = postMethod.getResponseBodyAsString(); return s; }
/** * Called upon initialization, Will create the ConfigParser and get the * RuleChain back. Will also configure the httpclient. * * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { log = LogFactory.getLog(ProxyFilter.class); AllowedMethodHandler.setAllowedMethods("OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE"); httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false); httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); String data = filterConfig.getInitParameter("dataUrl"); if (data == null) { serverChain = null; } else { try { File dataFile = new File(filterConfig.getServletContext().getRealPath(data)); ConfigParser parser = new ConfigParser(dataFile); serverChain = parser.getServerChain(); } catch (Exception e) { throw new ServletException(e); } } }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); httpClient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); httpClient.getHttpConnectionManager().getParams().setParameter("http.socket.timeout", TIMEOUT_SOCKET); httpClient.getHttpConnectionManager().getParams() .setSoTimeout(TIMEOUT_SOCKET); httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
/** * Basic constructor sets the listener to notify when * servers goes down/up. Also sets the polling time * which decides how long we wait between doing checks. * * @param listener The listener * @param pollingTime The time we wait between checks, in milliseconds */ public ServerStatusChecker(ServerStatusListener listener, long pollingTime) { this.listener = listener; this.pollingTime = Math.max(30*1000, pollingTime); setPriority(Thread.NORM_PRIORITY-1); setDaemon(true); online = new LinkedList(); offline = new LinkedList(); httpClient = new HttpClient(); httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false); httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); }
@Override public void initClient(final ConnectionSettings settings) { if (settings == null) throw new NullPointerException("Internet connection settings cannot be null"); this.settings = settings; final HttpClientParams clientParams = client.getParams(); clientParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); clientParams.setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); clientParams.setSoTimeout(timeout); clientParams.setConnectionManagerTimeout(timeout); clientParams.setHttpElementCharset("UTF-8"); this.client.setHttpConnectionManager(new SimpleHttpConnectionManager(/*true*/)); this.client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); HttpState initialState = new HttpState(); HostConfiguration configuration = new HostConfiguration(); if (settings.getProxyType() == Proxy.Type.SOCKS) { // Proxy stuff happens here configuration = new HostConfigurationWithStickyProtocol(); Proxy proxy = new Proxy(settings.getProxyType(), // create custom Socket factory new InetSocketAddress(settings.getProxyURL(), settings.getProxyPort()) ); protocol = new Protocol("http", new ProxySocketFactory(proxy), 80); } else if (settings.getProxyType() == Proxy.Type.HTTP) { // we use build in HTTP Proxy support configuration.setProxy(settings.getProxyURL(), settings.getProxyPort()); if (settings.getUserName() != null) initialState.setProxyCredentials(AuthScope.ANY, new NTCredentials(settings.getUserName(), settings.getPassword(), "", "")); } client.setHostConfiguration(configuration); clientParams.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); client.setState(initialState); }
public Stubs(ConfigurationContext ctx, String bbUrl) throws AxisFault { this.ctx = ctx; this.bbUrl = bbUrl; /* * Must use deprecated class of setting up security because the SOAP * response doesn't include a security header. Using the deprecated * OutflowConfiguration class we can specify that the security * header is only for the outgoing SOAP message. */ ofc = new OutflowConfiguration(); ofc.setActionItems("UsernameToken Timestamp"); ofc.setUser("session"); ofc.setPasswordType("PasswordText"); final MultiThreadedHttpConnectionManager conMan = new MultiThreadedHttpConnectionManager(); final HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxTotalConnections(1000); params.setDefaultMaxConnectionsPerHost(100); params.setSoTimeout(60000); params.setConnectionTimeout(30000); conMan.setParams(params); httpClient = new HttpClient(conMan); final HttpClientParams clientParams = httpClient.getParams(); clientParams.setAuthenticationPreemptive(false); clientParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ctx.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); contextWebservice = new ContextWSStub(ctx, PathUtils.filePath(bbUrl, "webapps/ws/services/Context.WS")); initStub(contextWebservice); }
/** * Return a textual representation of the cookie. * * @return string. */ public String toExternalForm() { CookieSpec spec = null; if (getVersion() > 0) { spec = CookiePolicy.getDefaultSpec(); } else { spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); } return spec.formatCookie(this); }
/** * Returns {@link CookiePolicy cookie policy} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} * this collection of parameters applies to. * * @return {@link CookiePolicy cookie policy} */ public String getCookiePolicy() { Object param = getParameter(COOKIE_POLICY); if (param == null) { return CookiePolicy.DEFAULT; } return (String)param; }
/** * Returns the actual cookie policy * * @param state HTTP state. TODO: to be removed in the future * * @return cookie spec */ private CookieSpec getCookieSpec(final HttpState state) { if (this.cookiespec == null) { int i = state.getCookiePolicy(); if (i == -1) { this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy()); } else { this.cookiespec = CookiePolicy.getSpecByPolicy(i); } this.cookiespec.setValidDateFormats( (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS)); } return this.cookiespec; }
protected void initHttpClient() { if (httpClient == null) { httpClient = new HttpClient(); } params = new HttpClientParams(); myCookie = new Cookie(".secq.me", "mycookie", "stuff", "/", null, false); initialState = new HttpState(); initialState.addCookie(myCookie); httpClient.setParams(params); httpClient.setState(initialState); httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); }
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials( AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } }
@Override public void setup(OperatorContext context) { url = prepareURL(); client = new HttpClient(); method = new GetMethod(url); DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
/** * Constructor */ public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) { super(connectionMgr); if (baseUri == null) { throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL"); } mBaseUri = baseUri; mInstanceNumber = sIntanceCounter++; Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient"); String userAgent = OwnCloudClientManagerFactory.getUserAgent(); getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); getParams().setCookiePolicy( CookiePolicy.IGNORE_COOKIES); getParams().setParameter( PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers PARAM_SINGLE_COOKIE_HEADER_VALUE); applyProxySettings(); clearCredentials(); }
protected static PostMethod httpPost(String path, String request, String user, String pwd) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url + path); postMethod.setRequestBody(request); postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); if (userAndPasswordAreNotBlank(user, pwd)) { postMethod.setRequestHeader("Cookie", "JSESSIONID="+ getCookie(user, pwd)); } httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
public HttpProxy(int timeout, String proxy) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setSoTimeout(timeout); httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); System.setProperty("jsse.enableSNIExtension", "false"); System.setProperty("sun.net.client.defaultConnectTimeout", "20000"); System.setProperty("sun.net.client.defaultReadTimeout", "20000"); proxy = "httpproxy-res.tan.ygrid.yahoo.com:4080"; ProxyHost p = new ProxyHost(proxy); httpClient.getHostConfiguration().setProxyHost(p); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); }
/** * Login the HttpClient based on the session cookie * * @param username * @param password * @param c * @throws HttpException * @throws IOException */ public HttpClient loginWithCookie(final String username, final String password) throws HttpException, IOException { final HttpClient c = getHttpClient(); final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build(); final GetMethod method = new GetMethod(uri.toString()); method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); final int response = c.executeMethod(method); final String body = method.getResponseBodyAsString(); method.releaseConnection(); assertTrue(response == 200); assertTrue(body != null && body.length() > "<hello></hello>".length()); return c; }
/** * Login the HttpClient based on the session cookie * * @param username * @param password * @param c * @throws HttpException * @throws IOException */ public void loginWithCookie(final String username, final String password, final HttpClient c) throws HttpException, IOException { final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build(); final GetMethod method = new GetMethod(uri.toString()); method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); final int response = c.executeMethod(method); final String body = method.getResponseBodyAsString(); method.releaseConnection(); assertTrue(response == 200); assertTrue(body != null && body.length() > "<hello></hello>".length()); }
public PutMethod createPut(final URI requestURI, final String accept, final boolean cookie) { final PutMethod method = new PutMethod(requestURI.toString()); if (cookie) { method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } if (StringHelper.containsNonWhitespace(accept)) { method.addRequestHeader("Accept", accept); } method.addRequestHeader("Accept-Language", "en"); return method; }
public PostMethod createPost(final URI requestURI, final String accept, final boolean cookie) { final PostMethod method = new PostMethod(requestURI.toString()); if (cookie) { method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } if (StringHelper.containsNonWhitespace(accept)) { method.addRequestHeader("Accept", accept); } return method; }
public DeleteMethod createDelete(final URI requestURI, final String accept, final boolean cookie) { final DeleteMethod method = new DeleteMethod(requestURI.toString()); if (cookie) { method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } if (StringHelper.containsNonWhitespace(accept)) { method.addRequestHeader("Accept", accept); } return method; }