public static HttpResponse execute(HttpClient httpClient, HttpUriRequest request, String tmpProxy) throws Exception { Object origProxy = httpClient.getParams().getParameter( ConnRouteParams.DEFAULT_PROXY); // 设置临时代理 setProxy(httpClient, tmpProxy); try { return httpClient.execute(request); } catch (Exception e) { throw e; } finally { // 恢复代理 httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, origProxy); } }
/** * Get a HttpClient object which is setting correctly . * * @param context * : context of activity * @return HttpClient: HttpClient object */ public static HttpClient getHttpClient(Context context) { BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParameters); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // 获取当前正在使用的APN接入点 Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // 游标移至第一条记录,当然也只有一条 String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; }
/** * apply a proxy to a httpClient, and setup proxy auth info if the httpClient is an instance of * {@link DefaultHttpClient} * */ public static void applyProxy(HttpClient httpClient, Proxy proxy) { Assert.notNull(httpClient, "httpClient is required"); Assert.notNull(proxy, "proxy is required"); String host = proxy.getHost(); int port = -1; if (proxy.getPort() > 0) { port = proxy.getPort(); } String schema = null; if (proxy.getSchema() != null) { schema = proxy.getSchema(); } HttpHost proxyHost = new HttpHost(host, port, schema); httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxyHost); if (httpClient instanceof DefaultHttpClient) { DefaultHttpClient defaultHttpClient = (DefaultHttpClient) httpClient; if (proxy.getUserName() != null) { defaultHttpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword())); } } }
@Override public Object getParameter(String name) { if (name.equals(ConnRouteParams.DEFAULT_PROXY)) { Proxy proxy = client.proxy(); if (proxy == null) { return null; } InetSocketAddress address = (InetSocketAddress) proxy.address(); return new HttpHost(address.getHostName(), address.getPort()); } throw new IllegalArgumentException(name); }
@Override public HttpParams setParameter(String name, Object value) { if (name.equals(ConnRouteParams.DEFAULT_PROXY)) { HttpHost host = (HttpHost) value; Proxy proxy = null; if (host != null) { proxy = new Proxy(HTTP, new InetSocketAddress(host.getHostName(), host.getPort())); } client = client.newBuilder() .proxy(proxy) .build(); return this; } throw new IllegalArgumentException(name); }
@Override public HttpRoute determineRoute(final HttpHost target, final HttpRequest request, final HttpContext context) throws HttpException { Args.notNull(request, "HTTP request"); // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) { return route; } // If we get here, there is no forced route. // So we need a target to compute a route. Asserts.notNull(target, "Target host"); final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = determineProxy(target, request, context); final Scheme schm = this.schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return route; }
public static void setUseProxy (boolean useProxy) { HttpParams params = getHttpClient().getParams(); if (useProxy) { try { params.setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost(Proxy.getDefaultHost(), Proxy.getDefaultPort())); } catch (Exception e) { e.printStackTrace(); } } else { params.removeParameter(ConnRouteParams.DEFAULT_PROXY); } }
/** * 获取有代理的 HttpClient * @return */ public HttpClient getProxyHttpClient() { DefaultHttpClient httpClient = new DefaultHttpClient(); String proxyHost = "10.195.113.100"; int proxyPort = 8002; String userName = "fushiguang"; String password = "Wisleyok1234"; httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(userName, password)); HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); return httpClient; }
/** * 设置httpclient默认代理 * * @param proxy * 格式 127.0.0.1:8080 */ public static void setProxy(HttpClient httpClient, String proxy) { if (proxy != null) { String[] tmp = proxy.split(":"); HttpHost proxyHost = new HttpHost(tmp[0], Integer.valueOf(tmp[1])); httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxyHost); } else { httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, null); } }
public static String getProxy(HttpClient httpClient) { HttpHost proxyHost = (HttpHost) httpClient.getParams().getParameter( ConnRouteParams.DEFAULT_PROXY); if (proxyHost == null) return null; return proxyHost.getHostName() + ":" + proxyHost.getPort(); }
@Override public Object getParameter(String name) { if (name.equals(ConnRouteParams.DEFAULT_PROXY)) { Proxy proxy = client.getProxy(); if (proxy == null) { return null; } InetSocketAddress address = (InetSocketAddress) proxy.address(); return new HttpHost(address.getHostName(), address.getPort()); } throw new IllegalArgumentException(name); }
@Override public HttpParams setParameter(String name, Object value) { if (name.equals(ConnRouteParams.DEFAULT_PROXY)) { HttpHost host = (HttpHost) value; Proxy proxy = null; if (host != null) { proxy = new Proxy(HTTP, new InetSocketAddress(host.getHostName(), host.getPort())); } client.setProxy(proxy); return this; } throw new IllegalArgumentException(name); }
@SuppressWarnings("deprecation") public static void setUseProxy (boolean useProxy) { HttpParams params = getHttpClient().getParams(); if (useProxy) { try { params.setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost(Proxy.getDefaultHost(), Proxy.getDefaultPort())); } catch (Exception e) { e.printStackTrace(); } } else { params.removeParameter(ConnRouteParams.DEFAULT_PROXY); } }
public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (request == null) { throw new IllegalStateException("Request must not be null."); } // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) { return route; } // If we get here, there is no forced route. // So we need a target to compute a route. if (target == null) { throw new IllegalStateException("Target host must not be null."); } final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxyChain == null || proxyChain.length == 0) { route = new HttpRoute(target, local, secure); } else { TunnelType tunnelType = secure ? TunnelType.TUNNELLED : TunnelType.PLAIN; LayerType layereType = secure ? LayerType.LAYERED : LayerType.PLAIN; return new HttpRoute(target, null, proxyChain, secure, tunnelType, layereType); } return route; }
/** * Executes the download in a separate thread */ public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo, mService); AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } client = AndroidHttpClient.newInstance(userAgent(), mContext); boolean finished = false; while (!finished) { if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } // Set or unset proxy, which may have changed since last GET // request. // setDefaultProxy() supports null as proxy parameter. ConnRouteParams.setDefaultProxy(client.getParams(), getPreferredHttpHost(mContext, state.mRequestUri)); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = DownloaderService.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage()); error.printStackTrace(); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex); finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount, state.mGotData, state.mFilename); } }
private static HttpClient buildClient(InetAddress localAddress) { HttpClient client = HttpClients.createMinimal(); client.getParams().setParameter(ConnRouteParams.LOCAL_ADDRESS, localAddress); return client; }
@Override public HttpRoute determineRoute(final HttpHost target, final HttpRequest request, final HttpContext context) throws HttpException { Args.notNull(request, "HTTP request"); // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) { return route; } // If we get here, there is no forced route. // So we need a target to compute a route. Asserts.notNull(target, "Target host"); final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = ConnRouteParams.getDefaultProxy(request.getParams()); final Scheme schm; try { schm = this.schemeRegistry.getScheme(target.getSchemeName()); } catch (final IllegalStateException ex) { throw new HttpException(ex.getMessage()); } // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return route; }
/** * Executes the download in a separate thread */ @SuppressLint("Wakelock") public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); State state = new State(mInfo, mService); AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; try { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } client = AndroidHttpClient.newInstance(userAgent(), mContext); boolean finished = false; while (!finished) { if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } // Set or unset proxy, which may have changed since last GET // request. // setDefaultProxy() supports null as proxy parameter. ConnRouteParams.setDefaultProxy(client.getParams(), getPreferredHttpHost(mContext, state.mRequestUri)); HttpGet request = new HttpGet(state.mRequestUri); try { executeDownload(state, client, request); finished = true; } catch (RetryDownload exc) { // fall through } finally { request.abort(); request = null; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mFileName); Log.v(Constants.TAG, " at " + mInfo.mUri); } finalizeDestinationFile(state); finalStatus = DownloaderService.STATUS_SUCCESS; } catch (StopRequest error) { // remove the cause before printing, in case it contains PII Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage()); error.printStackTrace(); finalStatus = error.mFinalStatus; // fall through to finally block } catch (Throwable ex) { // sometimes the socket code throws unchecked // exceptions Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex); finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } cleanupDestination(state, finalStatus); notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount, state.mGotData, state.mFilename); } }
public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (request == null) { throw new IllegalStateException ("Request must not be null."); } // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // If we get here, there is no forced route. // So we need a target to compute a route. if (target == null) { throw new IllegalStateException ("Target host must not be null."); } final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = ConnRouteParams.getDefaultProxy(request.getParams()); final Scheme schm = schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return route; }
public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (request == null) { throw new IllegalStateException ("Request must not be null."); } // If we have a forced route, we can do without a target. HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams()); if (route != null) return route; // If we get here, there is no forced route. // So we need a target to compute a route. if (target == null) { throw new IllegalStateException ("Target host must not be null."); } final InetAddress local = ConnRouteParams.getLocalAddress(request.getParams()); final HttpHost proxy = determineProxy(target, request, context); final Scheme schm = this.schemeRegistry.getScheme(target.getSchemeName()); // as it is typically used for TLS/SSL, we assume that // a layered scheme implies a secure connection final boolean secure = schm.isLayered(); if (proxy == null) { route = new HttpRoute(target, local, secure); } else { route = new HttpRoute(target, local, proxy, secure); } return route; }
public static HttpClient getNewHttpClient(Context context) { 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(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); if(context != null){ WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // 获取当前正在使用的APN接入点 Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // 游标移至第一条记录,当然也只有一条 String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); Log.d(TAG, "APN proxy:" + proxyStr); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } }else { Log.d(TAG, "connect to internet by wifi."); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
public static HttpClient getNewHttpClient(Context context) { 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(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // 获取当前正在使用的APN接入点 Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // 游标移至第一条记录,当然也只有一条 String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
public HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setUserAgent(params, ConnectioinConfig.userAgent); ConnManagerParams.setMaxTotalConnections(params, ConnectioinConfig.maxConnections); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute httproute) { return 32; } }); HttpClientParams.setRedirecting(params, true); params.setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, ConnectioinConfig.connectionTimeout); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, ConnectioinConfig.socketTimeout); params.setParameter( CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024); params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); params.setParameter( CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); // 默认为ISO-8859-1 params.setParameter( CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8"); // 默认为US-ASCII params.removeParameter(ConnRouteParams.DEFAULT_PROXY); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); ThreadSafeClientConnManager conMgr = new ThreadSafeClientConnManager( params, schReg); DefaultHttpClient client = new DefaultHttpClient(conMgr, params); //Auto retry. client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if(executionCount > ConnectioinConfig.maxRetryCount) return false; if(exception instanceof NoHttpResponseException) return true; if(exception instanceof SocketTimeoutException) return true; return false; } }); return client; }