Пример #1
0
  /**
   * Create a new HttpClient with reasonable defaults (which you can update).
   *
   * @param userAgent to report in your HTTP requests.
   * @return FailfastHttpClient for you to use for all your requests.
   */
  public static FailfastHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 10 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null) HttpProtocolParams.setUserAgent(params, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new FailfastHttpClient(manager, params);
  }
Пример #2
0
  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);
  }
Пример #3
0
  public HttpUtils(int connTimeout, String userAgent) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    if (TextUtils.isEmpty(userAgent)) {
      userAgent = OtherUtils.getUserAgent(null);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
              httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext httpContext)
              throws org.apache.http.HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                  response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                  return;
                }
              }
            }
          }
        });
  }
  private HttpResponse HttpClientPost(String URL, String upload) {
    BasicHttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    HttpClient httpclient = new DefaultHttpClient(httpParams);
    try {
      HttpPost post = new HttpPost(URL);
      post.addHeader("content-type", "application/x-www-form-urlencoded");
      post.setEntity(new StringEntity(upload));

      HttpResponse response = httpclient.execute(post);
      return response;
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
Пример #5
0
 private static final HttpParams createHttpParams() {
   final HttpParams params = new BasicHttpParams();
   HttpConnectionParams.setStaleCheckingEnabled(params, false);
   HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); // 设置参数连接时间
   HttpConnectionParams.setSoTimeout(params, 60 * 1000); // 设置参数连接超时时间
   HttpConnectionParams.setSocketBufferSize(params, 8192 * 5);
   return params;
 }
Пример #6
0
  /** Creates a new AsyncHttpClient. */
  public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(
        httpParams,
        String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
  }
 public RestClient(String url) {
   this.url = url;
   params = new ArrayList<NameValuePair>();
   headers = new ArrayList<NameValuePair>();
   httpRequestParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
   HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
   HttpConnectionParams.setSocketBufferSize(httpRequestParams, BUFFER_SIZE);
 }
Пример #8
0
  public Http(Context context) {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, 10);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    clientHeaderMap = new HashMap<String, String>();
  }
Пример #9
0
  /**
   * Generate and return a {@link HttpClient} configured for general use, including setting an
   * application-specific user-agent string.
   */
  public static HttpClient getHttpClient() {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    final DefaultHttpClient client = new DefaultHttpClient(params);

    return client;
  }
Пример #10
0
  /** Create the default HTTP protocol parameters. */
  private static final HttpParams createHttpParams() {

    final HttpParams params = new BasicHttpParams();

    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    return params;
  }
Пример #11
0
  private DefaultHttpClient getAdViewHttpClient() {
    HttpParams httpParameters = new BasicHttpParams();

    if (mTimeoutMilliseconds > 0) {
      // Set timeouts to wait for connection establishment / receiving data.
      HttpConnectionParams.setConnectionTimeout(httpParameters, mTimeoutMilliseconds);
      HttpConnectionParams.setSoTimeout(httpParameters, mTimeoutMilliseconds);
    }

    // Set the buffer size to avoid OutOfMemoryError exceptions on certain HTC devices.
    // http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
    HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);

    return new DefaultHttpClient(httpParameters);
  }
 /** initialize HttpParams , initialize settings such as total connextions,timeout ... */
 private BasicHttpParams createHttpParams() {
   BasicHttpParams params = new BasicHttpParams();
   ConnManagerParams.setTimeout(params, config.getConnectTimeout());
   ConnManagerParams.setMaxConnectionsPerRoute(
       params, new ConnPerRouteBean(DEFAULT_MAX_CONN_PER_ROUT));
   ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONN_TOTAL);
   HttpConnectionParams.setTcpNoDelay(params, TCP_NO_DELAY);
   HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
   HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
   HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(params, config.getUserAgent());
   // settingOthers(params);
   return params;
 }
  @Override
  protected HttpParams createHttpParams() {
    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // determine the release version from packaged version info
    final VersionInfo vi =
        VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.5)");

    return params;
  }
 @Override
 public void initConfig(HttpConfig config) {
   if (config == null) {
     config = new HttpConfig(null);
   }
   super.initConfig(config);
   retryHandler =
       new HttpRetryHandler(config.getRetrySleepMillis(), config.isRequestSentRetryEnabled());
   if (mHttpClient != null) {
     HttpParams params = mHttpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
     HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
     HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
     HttpProtocolParams.setUserAgent(params, config.getUserAgent());
     mHttpClient.setParams(params);
   }
 }
Пример #15
0
  /** Create the default HTTP protocol parameters. */
  private static final HttpParams createHttpParams(Context mContext) {
    final HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    // 加入代理
    HttpUtils.fillProxy(mContext, params);
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    return params;
  }
Пример #16
0
  public DBhttpRequest() {
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    httpClient = new DefaultHttpClient(conMgr, params);
  }
 @Override
 protected void setConfigForHttpParams(
     int connectTimeout, int socketTimeout, int socketBufferSize) {
   super.setConfigForHttpParams(connectTimeout, socketTimeout, socketBufferSize);
   if (mHttpClient != null) {
     HttpParams params = mHttpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, config.getConnectTimeout());
     HttpConnectionParams.setSoTimeout(params, config.getSocketTimeout());
     HttpConnectionParams.setSocketBufferSize(params, config.getSocketBufferSize());
     mHttpClient.setParams(params);
     HttpLog.i(
         TAG,
         "lite-http set connectTimeout"
             + connectTimeout
             + " , socketTimeout: "
             + socketTimeout
             + " , socketBufferSize: "
             + socketBufferSize);
   }
 }
Пример #18
0
  @SuppressLint("NewApi")
  public static DefaultHttpClient createHttpClient(String userAgent, boolean redirecting) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Set the timeout in milliseconds until a connection is established. The default value is zero,
    // that means the timeout is not used.
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting
    // for data.
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, redirecting);

    HttpProtocolParams.setUserAgent(params, userAgent);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    // Set the specified user agent and register standard protocols.
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (AndroidUtils.isFroyo())
      schemeRegistry.register(
          new Scheme(
              "https",
              SSLCertificateSocketFactory.getHttpSocketFactory(SOCKET_OPERATION_TIMEOUT, null),
              443));
    else schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    final ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    return new DefaultHttpClient(manager, params);
  }
Пример #19
0
  static {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    HttpClientParams.setRedirecting(params, true); // GJT: Changed this to
    // true

    HttpProtocolParams.setUserAgent(params, "Shelves/1.1");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    sClient = new DefaultHttpClient(manager, params);
  }
  public static HttpClient newInstance() {
    HttpParams params = new BasicHttpParams();
    // 不自动处理重定向请求
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);
    HttpConnectionParams.setTcpNoDelay(params, true);
    ConnManagerParams.setMaxTotalConnections(params, 50);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean();
    connPerRoute.setDefaultMaxPerRoute(4);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", socketFactory, 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(manager, params);
  }
  private HttpResponse HttpClientget(String URL) {
    BasicHttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);

    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    HttpClient httpclient = new DefaultHttpClient(httpParams);
    try {
      HttpResponse response = httpclient.execute(new HttpGet(URL));
      return response;
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
  /** Constructor */
  public JsonRpcOauthOnlineService() {
    super();
    // setup oauth parameters
    mParameters = new BasicHttpParams();
    HttpProtocolParams.setVersion(mParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(mParameters, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(mParameters, false);
    HttpConnectionParams.setTcpNoDelay(mParameters, true);
    HttpConnectionParams.setSocketBufferSize(mParameters, 8192);

    // Set the timeout in milliseconds until a connection is established
    int timeoutConn = 10000;
    HttpConnectionParams.setConnectionTimeout(mParameters, timeoutConn);
    // Set the default socket timeout in milliseconds for waiting for data
    int timeoutSocket = 15000;
    HttpConnectionParams.setSoTimeout(mParameters, timeoutSocket);

    // setup oauth consumer
    mConsumer =
        new CommonsHttpOAuthConsumer(
            AppSettings.getInstance().getConsumerKey(),
            AppSettings.getInstance().getConsumerSecret());
  }
  /**
   * {@inheritDoc} <br>
   * <br>
   * The default implementation does all of this and more, including using a connection pool and
   * killing connections after a timeout to use less battery power on mobile devices. It's unlikely
   * that you'll want to change this behavior.
   */
  @Override
  public synchronized HttpClient getHttpClient() {
    if (client == null) {
      // Set up default connection params. There are two routes to
      // Dropbox - api server and content server.
      HttpParams connParams = new BasicHttpParams();
      ConnManagerParams.setMaxConnectionsPerRoute(
          connParams,
          new ConnPerRoute() {
            @Override
            public int getMaxForRoute(HttpRoute route) {
              return 10;
            }
          });
      ConnManagerParams.setMaxTotalConnections(connParams, 20);

      // Set up scheme registry.
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      DBClientConnManager cm = new DBClientConnManager(connParams, schemeRegistry);

      try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(
            null,
            new TrustManager[] {
              new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                  System.out.println("getAcceptedIssuers =============");
                  return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                  System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                  System.out.println("checkServerTrusted =============");
                }
              }
            },
            new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        schemeRegistry.register(httpsScheme);
      } catch (Exception e) {
        e.printStackTrace();
      }
      schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

      // Set up client params.
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
      HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
      HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
      HttpProtocolParams.setUserAgent(
          httpParams, "OfficialDropboxJavaSDK/" + DropboxAPI.SDK_VERSION);

      DefaultHttpClient c =
          new DefaultHttpClient(cm, httpParams) {
            @Override
            protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
              return new DBKeepAliveStrategy();
            }

            @Override
            protected ConnectionReuseStrategy createConnectionReuseStrategy() {
              return new DBConnectionReuseStrategy();
            }
          };

      c.addRequestInterceptor(
          new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });

      c.addResponseInterceptor(
          new HttpResponseInterceptor() {
            @Override
            public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
              HttpEntity entity = response.getEntity();
              if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                  HeaderElement[] codecs = ceheader.getElements();
                  for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                      response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                      return;
                    }
                  }
                }
              }
            }
          });

      client = c;
    }

    return client;
  }
Пример #24
0
  /**
   * http网页内容抓取
   *
   * @param url String 网页地址
   * @param timeoutSeconds int 超时时间(单位秒)
   * @param params Map<String, String> HTTPHead参数
   * @param cookieStore CookieStore 网页cookie
   * @return
   */
  public static String sendGet(
      Context mContext,
      String url,
      int timeoutSeconds,
      Map<String, String> params,
      CookieStore cookieStore,
      boolean isSaveCookie) {
    String result = null;
    Log.v(TAG, "httpGet start to get url:" + url);
    HttpParams httpParams = new BasicHttpParams();
    HttpContext context = new BasicHttpContext();

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
      Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点
      Cursor mCursor = mContext.getContentResolver().query(uri, null, null, null, null);
      if (mCursor != null && mCursor.getCount() > 0) {
        mCursor.moveToNext();
        String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
        if (proxyStr != null && proxyStr.trim().length() > 0) {
          Log.v(TAG, "wap proxy:" + proxyStr);
          HttpHost proxy = new HttpHost(proxyStr, 80);
          httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }
      }
    }

    HttpConnectionParams.setConnectionTimeout(httpParams, timeoutSeconds * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSeconds * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

    HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

    if (cookieStore != null) {

      httpClient.setCookieStore(cookieStore);
      context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }

    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(
        "User-Agent",
        "Mozilla/5.0 (Linux; U; Android "
            + Build.VERSION.RELEASE
            + "; Zh-cn; "
            + Build.MODEL
            + " )AppleWebKit/528.5+(KHTML,like Gecko)Version/3.1.2 Mobile Safari/525.20.1");
    if (params != null) {
      Iterator<String> ite = params.keySet().iterator();
      while (ite.hasNext()) {
        String key = (String) ite.next();
        String value = (String) params.get(key);
        httpGet.addHeader(key, value);
      }
    }
    try {
      HttpResponse response = httpClient.execute(httpGet, context);
      if (isSaveCookie) {
        CookieStore cookieStores = httpClient.getCookieStore();
        if (cookieStores != null) {
          List<Cookie> listCookie = cookieStores.getCookies();
          int len = listCookie.size();
          for (int i = 0; i < len; i++) {
            Cookie cookie = listCookie.get(i);
            StringBuffer sb = new StringBuffer();
            sb.append(cookie.getName() + "=" + cookie.getValue() + ";\n");
            sb.append("domain=" + cookie.getDomain() + ";\n");
            sb.append("path=" + cookie.getPath() + ";\n");
            sb.append("expiry=" + cookie.getExpiryDate() + ";\n");
            Log.i(TAG, sb.toString());
          }
        }
        //				Config.getInstance().setCookieStroe(httpClient.getCookieStore());
      }
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        result = EntityUtils.toString(response.getEntity());
      } else {
        Log.v(TAG, "result:" + EntityUtils.toString(response.getEntity()));
        result = MessageModel.RESPONSE_EXCEPTION;
        Log.e(TAG, "Network Exception, statusCode:" + statusCode);
      }
    } catch (Exception e) {
      if (e instanceof SocketTimeoutException) {
        result = MessageModel.CONNECTION_TIMEOUT;
        Log.e(TAG, "CONNECTION_TIMEOUT---- Network Exception:" + e.getMessage() + " url:" + url);
        e.printStackTrace();
      } else {
        result = MessageModel.RESPONSE_EXCEPTION;
        Log.e(TAG, "RESPONSE_EXCEPTION ---- Network Exception:" + e.getMessage() + " url:" + url);
        e.printStackTrace();
      }
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    Log.v(TAG, "httpGet get result:" + result);
    return result;
  }
Пример #25
0
  /**
   * Creates a new AsyncHttpClient and set timeout.
   *
   * @param timeout 超时时间
   */
  public AsyncHttpClient(int timeout) {
    this.socketTimeout = timeout;
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(
        httpParams,
        String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory sf = null;
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      sf = new MySSLSocketFactory(trustStore);
    } catch (Exception e) {
      e.printStackTrace();
    }
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
              request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
              request.addHeader(header, clientHeaderMap.get(header));
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                  response.setEntity(new InflatingEntity(response.getEntity()));
                  break;
                }
              }
            }
          }
        });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));
    /*   HttpHost proxy = NetworkUtils.getHttpHostProxy();
            if (proxy!=null) { // set proxy
            	  httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    		}
    */ threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
  }
  /**
   * Opens the connection to a http server or proxy.
   *
   * @return the opened low level connection
   * @throws IOException if the connection fails for any reason.
   */
  @Override
  AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    if (mProxyHost != null) {
      // If we have a proxy set, we first send a CONNECT request
      // to the proxy; if the proxy returns 200 OK, we negotiate
      // a secure connection to the target server via the proxy.
      // If the request fails, we drop it, but provide the event
      // handler with the response status and headers. The event
      // handler is then responsible for cancelling the load or
      // issueing a new request.
      AndroidHttpClientConnection proxyConnection = null;
      Socket proxySock = null;
      try {
        proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());

        proxySock.setSoTimeout(60 * 1000);

        proxyConnection = new AndroidHttpClientConnection();
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        proxyConnection.bind(proxySock, params);
      } catch (IOException e) {
        if (proxyConnection != null) {
          proxyConnection.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to establish a connection to the proxy";
        }

        throw new IOException(errorMessage);
      }

      StatusLine statusLine = null;
      int statusCode = 0;
      Headers headers = new Headers();
      try {
        BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());

        // add all 'proxy' headers from the original request, we also need
        // to add 'host' header unless we want proxy to answer us with a
        // 400 Bad Request
        for (Header h : req.mHttpRequest.getAllHeaders()) {
          String headerName = h.getName().toLowerCase(Locale.ROOT);
          if (headerName.startsWith("proxy")
              || headerName.equals("keep-alive")
              || headerName.equals("host")) {
            proxyReq.addHeader(h);
          }
        }

        proxyConnection.sendRequestHeader(proxyReq);
        proxyConnection.flush();

        // it is possible to receive informational status
        // codes prior to receiving actual headers;
        // all those status codes are smaller than OK 200
        // a loop is a standard way of dealing with them
        do {
          statusLine = proxyConnection.parseResponseHeader(headers);
          statusCode = statusLine.getStatusCode();
        } while (statusCode < HttpStatus.SC_OK);
      } catch (ParseException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (HttpException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      } catch (IOException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to send a CONNECT request";
        }

        throw new IOException(errorMessage);
      }

      if (statusCode == HttpStatus.SC_OK) {
        try {
          sslSock =
              (SSLSocket)
                  getSocketFactory()
                      .createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
        } catch (IOException e) {
          if (sslSock != null) {
            sslSock.close();
          }

          String errorMessage = e.getMessage();
          if (errorMessage == null) {
            errorMessage = "failed to create an SSL socket";
          }
          throw new IOException(errorMessage);
        }
      } else {
        // if the code is not OK, inform the event handler
        ProtocolVersion version = statusLine.getProtocolVersion();

        req.mEventHandler.status(
            version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
        req.mEventHandler.headers(headers);
        req.mEventHandler.endData();

        proxyConnection.close();

        // here, we return null to indicate that the original
        // request needs to be dropped
        return null;
      }
    } else {
      // if we do not have a proxy, we simply connect to the host
      try {
        sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
        sslSock.setSoTimeout(SOCKET_TIMEOUT);
      } catch (IOException e) {
        if (sslSock != null) {
          sslSock.close();
        }

        String errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "failed to create an SSL socket";
        }

        throw new IOException(errorMessage);
      }
    }

    // do handshake and validate server certificates
    SslError error =
        CertificateChainValidator.getInstance()
            .doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());

    // Inform the user if there is a problem
    if (error != null) {
      // handleSslErrorRequest may immediately unsuspend if it wants to
      // allow the certificate anyway.
      // So we mark the connection as suspended, call handleSslErrorRequest
      // then check if we're still suspended and only wait if we actually
      // need to.
      synchronized (mSuspendLock) {
        mSuspended = true;
      }
      // don't hold the lock while calling out to the event handler
      boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
      if (!canHandle) {
        throw new IOException("failed to handle " + error);
      }
      synchronized (mSuspendLock) {
        if (mSuspended) {
          try {
            // Put a limit on how long we are waiting; if the timeout
            // expires (which should never happen unless you choose
            // to ignore the SSL error dialog for a very long time),
            // we wake up the thread and abort the request. This is
            // to prevent us from stalling the network if things go
            // very bad.
            mSuspendLock.wait(10 * 60 * 1000);
            if (mSuspended) {
              // mSuspended is true if we have not had a chance to
              // restart the connection yet (ie, the wait timeout
              // has expired)
              mSuspended = false;
              mAborted = true;
              if (HttpLog.LOGV) {
                HttpLog.v(
                    "HttpsConnection.openConnection():"
                        + " SSL timeout expired and request was cancelled!!!");
              }
            }
          } catch (InterruptedException e) {
            // ignore
          }
        }
        if (mAborted) {
          // The user decided not to use this unverified connection
          // so close it immediately.
          sslSock.close();
          throw new SSLConnectionClosedByUserException("connection closed by the user");
        }
      }
    }

    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);

    return conn;
  }
 public AsyncHttpClient() {
   HttpParams basicHttpParams = new BasicHttpParams();
   ConnManagerParams.setTimeout(basicHttpParams, (long) socketTimeout);
   ConnManagerParams.setMaxConnectionsPerRoute(
       basicHttpParams, new ConnPerRouteBean(maxConnections));
   ConnManagerParams.setMaxTotalConnections(basicHttpParams, DEFAULT_MAX_CONNECTIONS);
   HttpConnectionParams.setSoTimeout(basicHttpParams, socketTimeout);
   HttpConnectionParams.setConnectionTimeout(basicHttpParams, socketTimeout);
   HttpConnectionParams.setTcpNoDelay(basicHttpParams, true);
   HttpConnectionParams.setSocketBufferSize(basicHttpParams, DEFAULT_SOCKET_BUFFER_SIZE);
   HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setUserAgent(
       basicHttpParams,
       String.format(
           "android-async-http/%s (http://loopj.com/android-async-http)", new Object[] {VERSION}));
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(
       new Scheme(MediaService.DEFAULT_MEDIA_DELIVERY, PlainSocketFactory.getSocketFactory(), 80));
   schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
   ClientConnectionManager threadSafeClientConnManager =
       new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry);
   this.httpContext = new SyncBasicHttpContext(new BasicHttpContext());
   this.httpClient = new DefaultHttpClient(threadSafeClientConnManager, basicHttpParams);
   this.httpClient.addRequestInterceptor(
       new HttpRequestInterceptor() {
         public void process(HttpRequest httpRequest, HttpContext httpContext) {
           if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
             httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
           }
           Iterator it = AsyncHttpClient.this.clientHeaderMap.keySet().iterator();
           while (it.hasNext()) {
             String str = (String) it.next();
             httpRequest.addHeader(str, (String) AsyncHttpClient.this.clientHeaderMap.get(str));
           }
         }
       });
   this.httpClient.addResponseInterceptor(
       new HttpResponseInterceptor() {
         public void process(HttpResponse httpResponse, HttpContext httpContext) {
           HttpEntity entity = httpResponse.getEntity();
           if (entity != null) {
             Header contentEncoding = entity.getContentEncoding();
             if (contentEncoding != null) {
               HeaderElement[] elements = contentEncoding.getElements();
               int length = elements.length;
               int i = 0;
               while (i < length) {
                 if (elements[i].getName().equalsIgnoreCase(ENCODING_GZIP)) {
                   httpResponse.setEntity(new InflatingEntity(httpResponse.getEntity()));
                   return;
                 } else {
                   i++;
                 }
               }
             }
           }
         }
       });
   this.httpClient.setHttpRequestRetryHandler(new RetryHandler(5));
   this.threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
   this.requestMap = new WeakHashMap();
   this.clientHeaderMap = new HashMap();
 }