private HttpClient getHttpClient() {
   if (null == customerHttpClient) {
     HttpParams params = new BasicHttpParams();
     // 设置一些基本参数
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
     HttpProtocolParams.setUseExpectContinue(params, true);
     HttpProtocolParams.setUserAgent(params, "Linux; Android 2.2.1;zh-CN; itkt_Android");
     //			HttpClientParams.setRedirecting(params, true);
     //		    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
     // 设置最大连接数
     ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS);
     // 设置获取连接的最大等待时间
     ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
     // 设置每个路由最大连接数
     ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
     ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
     // 设置连接超时时间
     HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
     // 设置读取超时时间
     HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
     try {
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       SchemeRegistry schReg = new SchemeRegistry();
       schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       // 使用线程安全的连接管理来创建HttpClient
       ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
       customerHttpClient = new DefaultHttpClient(conMgr, params);
       customerHttpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return customerHttpClient;
 }
Ejemplo n.º 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);
  }
Ejemplo n.º 3
0
    public org.apache.http.client.HttpClient configureClient() {
      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setUseExpectContinue(params, useExpectContinue);
      HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
      HttpConnectionParams.setSoTimeout(params, socketTimeout);
      HttpConnectionParams.setTcpNoDelay(params, Boolean.TRUE);

      String protocol = "http";

      if (enableSSL) protocol = "https";

      params.setParameter(ClientPNames.DEFAULT_HOST, new HttpHost(host, port, protocol));
      if (proxy != null) {
        params.setParameter(
            ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy, proxyPort, protocol));
      }
      DefaultHttpClient client = new DefaultHttpClient(configureConnectionManager(params), params);
      if (username != null && password != null) {
        client
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(host, port, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
        client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);
      }

      return client;
    }
  /**
   * Call to execute post request
   *
   * @param method - url
   * @param envelope - string envelope for post request
   * @param headers - headrs for request
   * @return - HttpResult instance for response
   */
  public static HttpResult post(String method, String envelope, Map<String, String> headers) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    /** set params t request */
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT);
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
    /** set url */
    HttpPost httpPost = new HttpPost(method);
    /** set headers */
    if (headers != null) {
      for (Map.Entry<String, String> header : headers.entrySet())
        httpPost.setHeader(header.getKey(), header.getValue());
    }
    /** execute request and generate HttpResult instance */
    final HttpResult resultHttpResult = new HttpResult();
    try {
      /** set envelope for post request */
      envelope = new String(envelope.getBytes("UTF-8"), "UTF-8");
      HttpEntity entity = new StringEntity(envelope, HTTP.UTF_8);
      httpPost.setEntity(entity);
      /** execute request */
      String resultEnvelope =
          httpClient.execute(httpPost, new DefaultResponseHandler(resultHttpResult));
      resultHttpResult.setEnvelope(resultEnvelope);
    } catch (ClientProtocolException ignored) {
    } catch (IOException ignored) {
    }

    return resultHttpResult;
  }
Ejemplo n.º 5
0
 private static DefaultHttpClient createHttpsClient() {
   DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
   DefaultHttpClient defaulthttpclient1;
   try {
     KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
     keystore.load(null, null);
     CustomSSLSocketFactory customsslsocketfactory = new CustomSSLSocketFactory(keystore);
     customsslsocketfactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
     BasicHttpParams basichttpparams = new BasicHttpParams();
     HttpProtocolParams.setVersion(basichttpparams, HttpVersion.HTTP_1_1);
     HttpProtocolParams.setContentCharset(basichttpparams, "utf-8");
     HttpProtocolParams.setUseExpectContinue(basichttpparams, false);
     HttpConnectionParams.setConnectionTimeout(basichttpparams, HttpConst.NETWORK_TIME_OUT);
     HttpConnectionParams.setSoTimeout(basichttpparams, HttpConst.NETWORK_TIME_OUT);
     SchemeRegistry schemeregistry = new SchemeRegistry();
     schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
     schemeregistry.register(new Scheme("https", customsslsocketfactory, 443));
     defaulthttpclient1 =
         new DefaultHttpClient(
             new ThreadSafeClientConnManager(basichttpparams, schemeregistry), basichttpparams);
     defaulthttpclient1
         .getCredentialsProvider()
         .setCredentials(
             new AuthScope(null, -1), new UsernamePasswordCredentials("admin", "admin"));
     defaulthttpclient = defaulthttpclient1;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return defaulthttpclient;
 }
Ejemplo n.º 6
0
  protected DefaultHttpClient getHttpClient() {
    if (httpClient == null) {
      HttpParams httpParams = new BasicHttpParams();
      HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
      HttpProtocolParams.setUseExpectContinue(
          httpParams, false); // some webservers have problems if this is set to true
      ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS);
      HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);

      //            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new
      // HttpHost("192.168.16.180", 8888, "http"));
      httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

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

      ClientConnectionManager connectionManager =
          new ThreadSafeClientConnManager(httpParams, schemeRegistry);

      httpClient = new DefaultHttpClient(connectionManager, httpParams);
    }

    return httpClient;
  }
Ejemplo n.º 7
0
  public static synchronized HttpClient getHttpClient() {
    if (null == customerHttpClient) {
      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params,
          "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
              + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

      // 从连接池中取连续的超时时间
      ConnManagerParams.setTimeout(params, 1000);
      HttpConnectionParams.setConnectionTimeout(params, 2000);
      HttpConnectionParams.setSoTimeout(params, 4000);

      // 设置我们的HttpClient支持HTTP和HTTPS两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
      customerHttpClient = new DefaultHttpClient(conMgr, params);
    }
    return customerHttpClient;
  }
Ejemplo n.º 8
0
  public void post(FileEntity fileEntity) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(fileEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      //
    }
  }
  // 每次都返回新的HttpClient实例
  public static HttpClient getNewInstance(Context mContext) {
    HttpClient newInstance;

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    // 自定义三个timeout参数

    /*
     * 1.set a timeout for the connection manager,it defines how long we
     * should wait to get a connection out of the connection pool managed by
     * the connection manager
     */
    ConnManagerParams.setTimeout(params, 5000);

    /*
     * 2.The second timeout value defines how long we should wait to make a
     * connection over the network to the server on the other end
     */
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);

    /*
     * 3.we set a socket timeout value to 4 seconds to define how long we
     * should wait to get data back for our request.
     */
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);

    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);

    newInstance = new DefaultHttpClient(conMgr, params);

    switch (checkNetworkType(mContext)) {
      case TYPE_CT_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.200访问www");
        }
        break;
      case TYPE_CM_CU_WAP:
        {
          // 通过代理解决中国移动联通GPRS中wap无法访问的问题
          HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
          newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
          Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.172访问www");
        }
        break;
    }
    return newInstance;
  }
Ejemplo n.º 10
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri) {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    client = getNewHttpClient();
  }
Ejemplo n.º 11
0
 private HttpClient createHttpClient() {
   HttpParams params = new BasicHttpParams();
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
   HttpProtocolParams.setUseExpectContinue(params, true);
   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);
   return new DefaultHttpClient(conMgr, params);
 }
Ejemplo n.º 12
0
 static {
   HttpParams params = new BasicHttpParams();
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(params, "UTF-8");
   HttpProtocolParams.setUserAgent(params, WeaveConstants.USER_AGENT);
   HttpProtocolParams.setUseExpectContinue(params, false);
   //    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
   params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
   params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
   sm_httpParams = params;
 }
  /**
   * Main constructor class for setting up the client that the specific Places/Context clients
   * extend from.
   */
  protected AbstractSimpleGeoClient() {

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORT, SSLSocketFactory.getSocketFactory()));
    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);

    this.httpClient = new OAuthHttpClient(connManager, params);
    this.threadExecutor = new RequestThreadPoolExecutor("SimpleGeoClient");
    endpoints.put("features", "1.0/features/%s.json");
    endpoints.put("annotations", "1.0/features/%s/annotations.json");
  }
Ejemplo n.º 14
0
  public byte[] post(String postBody, String contentType) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);

    StringEntity stringEntity = new StringEntity(postBody);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(stringEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

      if (response.getEntity() != null) {
        response.getEntity().writeTo(baos);
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return body;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }
Ejemplo n.º 15
0
  public static synchronized HttpClient getInstance(Context context) {
    if (null == customerHttpClient) {

      HttpParams params = new BasicHttpParams();

      // 设置一些基本参数
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, CHARSET);
      HttpProtocolParams.setUseExpectContinue(params, true);
      HttpProtocolParams.setUserAgent(
          params, System.getProperties().getProperty("http.agent") + " Mozilla/5.0 Firefox/26.0");

      // 超时设置
      /* 从连接池中取连接的超时时间 */
      ConnManagerParams.setTimeout(params, 10 * 1000);

      /* 连接超时 */
      HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);

      /* 请求超时 */
      HttpConnectionParams.setSoTimeout(params, 10 * 1000);

      // 支持http和https两种模式
      SchemeRegistry schReg = new SchemeRegistry();
      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schReg.register(new Scheme("https", getSSLSocketFactory(), 443));

      // 使用线程安全的连接管理来创建HttpClient
      ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

      customerHttpClient = new DefaultHttpClient(conMgr, params);
      customerHttpClient.setHttpRequestRetryHandler(requestRetryHandler);
      ConnectivityManager manager =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      NetworkInfo networkinfo = manager.getActiveNetworkInfo();
      String net = networkinfo != null ? networkinfo.getExtraInfo() : null;

      // wifi的值为空
      if (!TextUtils.isEmpty(net)) {
        String proxyHost = getDefaultHost();

        if (!TextUtils.isEmpty(proxyHost)) {
          HttpHost proxy = new HttpHost(proxyHost, getDefaultPort(), "http");

          customerHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
      }
    }
    return customerHttpClient;
  }
Ejemplo n.º 16
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri, String httpuser, String httppasswd) {
    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    postMethod.addHeader("charset", "UTF-8");
    // UPDATE THE VERSION NUMBER BEFORE RELEASE! <3 Dan
    postMethod.addHeader("User-Agent", "evodroid/" + Constants.versionNumber);

    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    // username & password not needed
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(httpuser, httppasswd);

    // this gets connections working over https
    if (uri.getScheme() != null) {
      if (uri.getScheme().equals("https")) {
        if (uri.getPort() == -1)
          try {
            client = new ConnectionClient(creds, 443);
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
        else
          try {
            client = new ConnectionClient(creds, uri.getPort());
          } catch (KeyManagementException e) {
            client = new ConnectionClient(creds);
          } catch (NoSuchAlgorithmException e) {
            client = new ConnectionClient(creds);
          } catch (KeyStoreException e) {
            client = new ConnectionClient(creds);
          } catch (UnrecoverableKeyException e) {
            client = new ConnectionClient(creds);
          }
      } else {
        client = new ConnectionClient(creds);
      }
    } else {
      client = new ConnectionClient(creds);
    }

    serializer = Xml.newSerializer();
  }
Ejemplo n.º 17
0
  public void save(File file, HttpFetcherListener listener) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Connection", "close");

    HttpParams params = httpGet.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, userAgent);

    FileOutputStream out = null;

    int statusCode = -1;
    Map<String, String> headers = null;

    try {

      out = new FileOutputStream(file);

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpGet);

      statusCode = response.getStatusLine().getStatusCode();
      headers = mapHeaders(response.headerIterator());

      if (statusCode < 200 || statusCode >= 300) {
        throw new IOException("bad status code, downloading file " + statusCode);
      }

      if (response.getEntity() != null) {
        writeEntity(response.getEntity(), out, listener);
      }

      if (listener != null) {
        listener.onSuccess(new byte[0]);
      }

    } catch (Throwable e) {
      if (listener != null) {
        listener.onError(e, statusCode, headers);
      }
      Log.e(TAG, "Error downloading from: " + uri + ", e: " + e.getMessage());
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
Ejemplo n.º 18
0
  /**
   * XMLRPCClient constructor. Creates new instance based on server URI (Code contributed by sgayda2
   * from issue #17, and by erickok from ticket #10)
   *
   * @param XMLRPC server URI
   */
  public XMLRPCClient(URI uri) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    postMethod = new HttpPost(uri);
    postMethod.addHeader("Content-Type", "text/xml");

    // WARNING
    // I had to disable "Expect: 100-Continue" header since I had
    // two second delay between sending http POST request and POST body
    httpParams = postMethod.getParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    this.client =
        new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
  }
Ejemplo n.º 19
0
  private HttpClient createHttpClient() {
    if (mHttpClient != null) return mHttpClient;
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUseExpectContinue(params, true);

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

    mHttpClient = new DefaultHttpClient(conMgr, params);

    return mHttpClient;
  }
Ejemplo n.º 20
0
  // This method for POST with add parameters
  public void postContentParameters(String url, ArrayList<NameValuePair> pairs) throws Exception {

    BufferedReader in = null;
    // StringBuilder builder = new StringBuilder();
    HttpPost post = new HttpPost(url);
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    post.setParams(params);

    try {

      UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
      post.setEntity(formEntity);

      HttpResponse response = client.execute(post);

      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      String codeStatus = String.valueOf(statusCode);

      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      Log.d("status Code Post", codeStatus);

      StringBuffer sb = new StringBuffer("");
      Log.d("SB 1", sb.toString());

      String line = "";
      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      Log.d("SB 2", sb.toString());
      in.close();

    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // TODO: handle exception
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 21
0
  // This method for GET
  public String getHttp(String url) {

    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    HttpGet get = new HttpGet(url);
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    get.setParams(params);

    try {

      HttpResponse response = client.execute(get);

      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      String codeStatus = String.valueOf(statusCode);

      HttpEntity entity = response.getEntity();
      InputStream content = entity.getContent();
      reader = new BufferedReader(new InputStreamReader(content));
      String line;
      while ((line = reader.readLine()) != null) {
        builder.append(line);
      }

      Log.d("Status Code", codeStatus);

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          return null;
        }
      }
    }
    return builder.toString();
  }
Ejemplo n.º 22
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);
  }
Ejemplo n.º 23
0
  /**
   * 自定义参数
   *
   * @return
   */
  private static HttpParams getHttpParams() {
    HttpParams params = new BasicHttpParams();
    // http 版本
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 请求编码
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // .....
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(
        params,
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");

    // 超时设置
    /* 连接超时 4s */
    HttpConnectionParams.setConnectionTimeout(params, 1000 * 3);
    /* 请求超时 10s */
    HttpConnectionParams.setSoTimeout(params, 1000 * 2);

    return params;
  }
Ejemplo n.º 24
0
  public HttpProtocol() {
    // http settings
    params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "Aletheia " + Aletheia.VERSION);
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpRequestInterceptor[] interceptors = {
      // Required protocol interceptors
      new RequestContent(),
      new RequestTargetHost(),
      // Recommended protocol interceptors
      new RequestConnControl(),
      new RequestUserAgent(),
      new RequestExpectContinue()
    };

    httpproc = new ImmutableHttpProcessor(interceptors);
    httpexecutor = new HttpRequestExecutor();
  }
Ejemplo n.º 25
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    user = (EditText) findViewById(R.id.user);
    password = (EditText) findViewById(R.id.password);
    status = (EditText) findViewById(R.id.status);

    Button send = (Button) findViewById(R.id.send);

    send.setOnClickListener(onSend);

    client = new DefaultHttpClient();

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF_8");
    HttpProtocolParams.setUseExpectContinue(params, false);

    client.setParams(params);
  }
  /** 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());
  }
  private synchronized HttpClient initHttpClient(final BOSHClientConfig config) {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params, false);
    if (config != null && config.getProxyHost() != null && config.getProxyPort() != 0) {
      HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
      params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslFactory = SSLSocketFactory.getSocketFactory();
    sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    schemeRegistry.register(new Scheme("https", sslFactory, 443));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(cm, params);
  }
Ejemplo n.º 28
0
  public Object[] fetch(boolean gzip) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Connection", "close");

    HttpParams params = httpGet.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, userAgent);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response =
          (gzip ? DEFAULT_HTTP_CLIENT_GZIP : DEFAULT_HTTP_CLIENT).execute(httpHost, httpGet);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300) {
        throw new IOException(
            "bad status code, downloading file " + response.getStatusLine().getStatusCode());
      }

      Long date = Long.valueOf(0);

      Header[] headers = response.getAllHeaders();
      for (int i = 0; i < headers.length; i++) {
        if (headers[i].getName().startsWith("Last-Modified")) {
          try {
            date = DateUtils.parseDate(headers[i].getValue()).getTime();
          } catch (Exception e) {
          }
          break;
        }
      }

      if (response.getEntity() != null) {
        if (gzip) {
          String str = EntityUtils.toString(response.getEntity());
          baos.write(str.getBytes());
        } else {
          response.getEntity().writeTo(baos);
        }
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return new Object[] {body, date};

    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }
 private void settingOthers(BasicHttpParams params) {
   HttpConnectionParams.setLinger(params, DEFAULT_KEEP_LIVE);
   HttpConnectionParams.setStaleCheckingEnabled(params, false);
   HttpProtocolParams.setUseExpectContinue(params, false);
 }
Ejemplo n.º 30
0
    public void run() {
      try {
        Thread.sleep(10);
        if (DBG) {
          Log.d(LCAT, "send()");
        }
        /*
        Header[] h = request.getAllHeaders();
        for(int i=0; i < h.length; i++) {
        	Header hdr = h[i];
        	//Log.e(LCAT, "HEADER: " + hdr.toString());
        }
         */
        handler = new LocalResponseHandler(TiHTTPClient.this);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SocketFactory sslFactory;
        if (validatesSecureCertificate()) {
          sslFactory = SSLSocketFactory.getSocketFactory();
        } else {
          sslFactory = new NonValidatingSSLSocketFactory();
        }
        registry.register(new Scheme("https", sslFactory, 443));
        HttpParams params = new BasicHttpParams();

        if (timeout != -1) {
          HttpConnectionParams.setConnectionTimeout(params, timeout);
        }

        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(manager, params);

        if (credentials != null) {
          client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), credentials);
          credentials = null;
        }
        HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
        HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1);

        if (request instanceof BasicHttpEntityEnclosingRequest) {

          UrlEncodedFormEntity form = null;
          MultipartEntity mpe = null;

          if (nvPairs.size() > 0) {
            try {
              form = new UrlEncodedFormEntity(nvPairs, "UTF-8");
            } catch (UnsupportedEncodingException e) {
              Log.e(LCAT, "Unsupported encoding: ", e);
            }
          }

          if (parts.size() > 0 && needMultipart) {
            mpe = new MultipartEntity();
            for (String name : parts.keySet()) {
              Log.d(
                  LCAT,
                  "adding part "
                      + name
                      + ", part type: "
                      + parts.get(name).getMimeType()
                      + ", len: "
                      + parts.get(name).getContentLength());
              mpe.addPart(name, parts.get(name));
            }
            if (form != null) {
              try {
                ByteArrayOutputStream bos =
                    new ByteArrayOutputStream((int) form.getContentLength());
                form.writeTo(bos);
                mpe.addPart(
                    "form",
                    new StringBody(
                        bos.toString(),
                        "application/x-www-form-urlencoded",
                        Charset.forName("UTF-8")));
              } catch (UnsupportedEncodingException e) {
                Log.e(LCAT, "Unsupported encoding: ", e);
              } catch (IOException e) {
                Log.e(LCAT, "Error converting form to string: ", e);
              }
            }

            HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
            Log.d(LCAT, "totalLength=" + totalLength);

            /*ProgressEntity progressEntity = new ProgressEntity(mpe, new ProgressListener() {
            	public void progress(int progress) {
            		KrollCallback cb = getCallback(ON_SEND_STREAM);
            		if (cb != null) {
            			TiDict data = new TiDict();
            			data.put("progress", ((double)progress)/fTotalLength);
            			data.put("source", proxy);
            			cb.callWithProperties(data);
            		}
            	}
            });*/
            // e.setEntity(progressEntity);

            e.setEntity(mpe);
            e.addHeader("Length", totalLength + "");
          } else {
            handleURLEncodedData(form);
          }
        }
        if (DBG) {
          Log.d(LCAT, "Preparing to execute request");
        }
        String result = client.execute(host, request, handler);
        if (result != null) {
          Log.d(LCAT, "Have result back from request len=" + result.length());
        }
        connected = false;
        setResponseText(result);
        setReadyState(READY_STATE_DONE);
      } catch (Exception e) {
        Log.e(LCAT, "HTTP Error: " + e.getMessage(), e);
        sendError(e.getMessage());
      }
    }