Ejemplo n.º 1
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);
  }
  public static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

      SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

      try {
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
      } catch (Exception e2) {
        // can ignore
      }

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

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      return new DefaultHttpClient();
    }
  }
Ejemplo n.º 3
0
  /**
   * 获取HttpClient,不同的业务场景传入不同的连接超时、请求超时参数
   *
   * @param url 访问的url
   * @param timeOut 连接超时
   * @param soTimeout 请求超时
   * @return HttpClient
   */
  public static HttpClient getHttpClient(String url, int timeOut, int soTimeout) {
    if (timeOut == 0) {
      timeOut = CONN_TIME_OUT;
    }
    if (soTimeout == 0) {
      soTimeout = SO_TIME_OUT;
    }

    StringBuilder sb = new StringBuilder(5);
    sb.append(url).append(".").append(timeOut).append(".").append(soTimeout);
    String key = sb.toString();

    HttpClient httpclient = httpClientMap.get(key);
    if (httpclient == null) {
      httpclient = new DefaultHttpClient(connectionManager);
      HttpParams params = httpclient.getParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
      params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
      HttpClient tempClient = httpClientMap.putIfAbsent(key, httpclient);
      if (tempClient != null) {
        httpclient = tempClient;
      }
    }

    return httpclient;
  }
Ejemplo n.º 4
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;
    }
Ejemplo n.º 5
0
 private static HttpParams getHttpParams() {
   HttpParams params = new BasicHttpParams();
   params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
   params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
   params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
   HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
   return params;
 }
  public HttpClient4Sender() {
    clientParams.setParameter(
        CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
    clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_READ_TIMEOUT_MILLISECONDS);

    HttpProtocolParams.setVersion(clientParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(clientParams, "UTF-8");
  }
Ejemplo n.º 7
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;
 }
Ejemplo n.º 8
0
  protected @Nonnull HttpClient getClient(String url, boolean multipart) throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
      throw new InternalException("No context was specified for this request");
    }
    boolean ssl = url.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
      String proxyHost = p.getProperty("proxyHost");
      String proxyPort = p.getProperty("proxyPort");

      if (proxyHost != null) {
        int port = 0;

        if (proxyPort != null && proxyPort.length() > 0) {
          port = Integer.parseInt(proxyPort);
        }
        params.setParameter(
            ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http"));
      }
    }
    return new DefaultHttpClient(params);
  }
Ejemplo n.º 9
0
 /*  66:    */
 /*  67:    */ public static void setLocalAddress(HttpParams params, InetAddress local)
       /*  68:    */ {
   /*  69:180 */ if (params == null) {
     /*  70:181 */ throw new IllegalArgumentException("Parameters must not be null.");
     /*  71:    */ }
   /*  72:183 */ params.setParameter("http.route.local-address", local);
   /*  73:    */ }
  public void loginUGotFile() throws Exception {

    loginsuccessful = false;
    HttpParams params = new BasicHttpParams();
    params.setParameter(
        "http.useragent",
        "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    NULogger.getLogger().info("Trying to log in to ugotfile.com");
    HttpPost httppost = new HttpPost("http://ugotfile.com/user/login");
    httppost.setHeader("Cookie", phpsessioncookie);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("ugfLoginUserName", getUsername()));
    formparams.add(new BasicNameValuePair("ugfLoginPassword", getPassword()));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    httppost.setEntity(entity);
    HttpResponse httpresponse = httpclient.execute(httppost);
    if (httpresponse.getStatusLine().toString().contains("302")) {
      tmp = httpresponse.getLastHeader("Location").getValue();
      NULogger.getLogger().info("UGotFile Login success");
      loginsuccessful = true;
      username = getUsername();
      password = getPassword();
    } else {
      NULogger.getLogger().info("UGotFile login failed");
      loginsuccessful = false;
      username = "";
      password = "";
      showWarningMessage(Translation.T().loginerror(), HOSTNAME);
      accountUIShow().setVisible(true);
    }
  }
Ejemplo n.º 11
0
  private HttpResponse getHTTPResponse() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    // Clear down the local cookie store every time to make sure we don't have any left over cookies
    // influencing the test
    localContext.setAttribute(ClientContext.COOKIE_STORE, null);

    LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState);
    if (mimicWebDriverCookieState) {
      localContext.setAttribute(
          ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies()));
    }

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    requestMethod.setParams(httpRequestParameters);
    // TODO if post send map of variables, also need to add a post map setter

    LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI);
    return client.execute(requestMethod, localContext);
  }
Ejemplo n.º 12
0
  public String call(String url, Map<String, String> fields) {

    // create an HTTP request to a protected resource
    HttpGet request = new HttpGet(endpoint);

    HttpParams p = new BasicHttpParams();

    for (Entry<String, String> en : fields.entrySet()) {
      p.setParameter(en.getKey(), en.getValue());
    }

    request.setParams(p);

    // sign the request
    try {
      consumer2.sign(request);
    } catch (OAuthMessageSignerException e) {
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      e.printStackTrace();
    }

    // send the request
    HttpClient httpClient = new DefaultHttpClient();
    try {
      HttpResponse response = httpClient.execute(request);
      return convertStreamToString(response.getEntity().getContent());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 13
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;
  }
  /**
   * Perform an HTTP Status check and return the response code
   *
   * @return
   * @throws IOException
   */
  public int getHTTPStatusCode() throws IOException {

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();
    System.out.println("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
    if (this.mimicWebDriverCookieState) {
      localContext.setAttribute(
          ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));
    }
    HttpRequestBase requestMethod = this.httpRequestMethod.getRequestMethod();
    requestMethod.setURI(this.linkToCheck);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    requestMethod.setParams(httpRequestParameters);

    System.out.println(
        "Sending " + requestMethod.getMethod() + " request for: " + requestMethod.getURI());
    HttpResponse response = client.execute(requestMethod, localContext);
    System.out.println(
        "HTTP "
            + requestMethod.getMethod()
            + " request status: "
            + response.getStatusLine().getStatusCode());

    return response.getStatusLine().getStatusCode();
  }
Ejemplo n.º 15
0
  /*
   * Special thanks to Tobias Knell at
   * http://blog.synyx.de/2010/06/android-and-self-signed-ssl-certificates/
   * The following method prepares for the HTTPS connection.
   */
  private void networkSetup() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // HTTP scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // HTTPS scheme
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");
    clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
  }
Ejemplo n.º 16
0
 /*  27:    */
 /*  28:    */ public static void setDefaultProxy(HttpParams params, HttpHost proxy)
       /*  29:    */ {
   /*  30:101 */ if (params == null) {
     /*  31:102 */ throw new IllegalArgumentException("Parameters must not be null.");
     /*  32:    */ }
   /*  33:104 */ params.setParameter("http.route.default-proxy", proxy);
   /*  34:    */ }
Ejemplo n.º 17
0
 /*  47:    */
 /*  48:    */ public static void setForcedRoute(HttpParams params, HttpRoute route)
       /*  49:    */ {
   /*  50:143 */ if (params == null) {
     /*  51:144 */ throw new IllegalArgumentException("Parameters must not be null.");
     /*  52:    */ }
   /*  53:146 */ params.setParameter("http.route.forced-route", route);
   /*  54:    */ }
  /**
   * Creates an HttpClient with the specified userAgent string.
   *
   * @param userAgent the userAgent string
   * @return the client
   */
  public static HttpClient newHttpClient(String userAgent) {
    // AndroidHttpClient is available on all platform releases,
    // but is hidden until API Level 8
    try {
      Class<?> clazz = Class.forName("android.net.http.AndroidHttpClient");
      Method newInstance = clazz.getMethod("newInstance", String.class);
      Object instance = newInstance.invoke(null, userAgent);

      HttpClient client = (HttpClient) instance;

      // ensure we default to HTTP 1.1
      HttpParams params = client.getParams();
      params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

      // AndroidHttpClient sets these two parameters thusly by default:
      // HttpConnectionParams.setSoTimeout(params, 60 * 1000);
      // HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);

      // however it doesn't set this one...
      ConnManagerParams.setTimeout(params, 60 * 1000);

      return client;
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
  private HttpClient newHttpClient(String sslProtocol, HttpRequest request) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, httpTimeoutsProvider.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params, httpTimeoutsProvider.getSocketTimeout());

    // AG-1059: Need to follow redirects to ensure that if the host app is setup with Apache and
    // mod_jk we can still
    // fetch internal gadgets.
    if (request.getFollowRedirects()) {
      params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
      params.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);
    }
    params.setParameter(
        ClientPNames.DEFAULT_HEADERS,
        ImmutableSet.of(new BasicHeader("Accept-Encoding", "gzip, deflate")));
    DefaultHttpClient client = new DefaultHttpClient(params);
    // AG-1044: Need to use the JVM's default proxy configuration for requests.
    ProxySelectorRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);

    client.addResponseInterceptor(new GzipDeflatingInterceptor());
    client
        .getConnectionManager()
        .getSchemeRegistry()
        .register(new Scheme("https", new CustomSSLSocketFactory(sslProtocol), 443));
    return client;
  }
Ejemplo n.º 20
0
 public static void setMaxConnectionsPerRoute(HttpParams httpparams, ConnPerRoute connperroute) {
   if (httpparams == null) {
     throw new IllegalArgumentException("HTTP parameters must not be null.");
   } else {
     httpparams.setParameter("http.conn-manager.max-per-route", connperroute);
     return;
   }
 }
Ejemplo n.º 21
0
 /**
  * Sets the Proxy by it's hostname,port,username and password
  *
  * @param hostname the hostname (IP or DNS name)
  * @param port the port number. -1 indicates the scheme default port.
  * @param username the username
  * @param password the password
  */
 public void setProxy(String hostname, int port, String username, String password) {
   httpClient
       .getCredentialsProvider()
       .setCredentials(
           new AuthScope(hostname, port), new UsernamePasswordCredentials(username, password));
   final HttpHost proxy = new HttpHost(hostname, port);
   final HttpParams httpParams = this.httpClient.getParams();
   httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
 }
Ejemplo n.º 22
0
  /**
   * Takes the extracted base URI and parameters from the {@link RequestConfig} consolidated
   * parameter type and creates a {@link HttpRequestBase} of the designated method type.
   *
   * @param uri the {@link URI} whose parameters should be populated
   * @param annotatedParams the list of {@link Param}s and the parameter objects which were
   *     annotated with them; <b>Complex objects should supply a formatted version of their String
   *     representation via {@link Object#toString()}</b>
   * @param staticParams the list of {@link Request.Param}s and the parameter objects which were
   *     annotated with them <br>
   *     <br>
   * @return the created {@link HttpRequestBase} which is an instance of {@link HttpPost} <br>
   *     <br>
   * @throws Exception when the {@link HttpRequestBase} could not be created due to an exception
   *     <br>
   *     <br>
   * @since 1.1.3
   */
  private static HttpRequestBase populateDeleteParameters(
      URI uri, Map<Object, Param> annotatedParams, List<Request.Param> staticParams)
      throws Exception {

    HttpParams httpParams = new BasicHttpParams();

    for (Request.Param param : staticParams) httpParams.setParameter(param.name(), param.value());

    Set<Entry<Object, Param>> methodParams = annotatedParams.entrySet();

    for (Entry<Object, Param> entry : methodParams)
      httpParams.setParameter(entry.getValue().value(), entry.getKey().toString());

    HttpDelete httpDelete = new HttpDelete(uri);
    httpDelete.setParams(httpParams);

    return httpDelete;
  }
Ejemplo n.º 23
0
  private HttpUtils() {
    SchemeRegistry reg = new SchemeRegistry();
    // sslSocFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    reg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    params_ = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params_, 5000);
    HttpConnectionParams.setSoTimeout(params_, 3000);
    params_.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params_.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params_.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    // HttpProtocolParams.setVersion(params_, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(params_, reg);
    client_ = new DefaultHttpClient(connMgr, params_);
    // context_ = new BasicHttpContext();
  }
Ejemplo n.º 24
0
 private void initClient() {
   // TODO Auto-generated method stub
   client = new DefaultHttpClient();
   int TIMEOUT = 30 * 1000;
   HttpParams params = client.getParams();
   HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
   HttpConnectionParams.setSoTimeout(params, TIMEOUT);
   params.setParameter(
       "User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0");
   params.setParameter(
       "http.useragent", "Mozilla/5.0 (X11; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0");
   params.setParameter("Accept-Language", "zh-CN,zh;q=0.8");
   params.setParameter("Accept-Encoding", "gzip,deflate,sdch");
   params.setParameter(
       "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
   client.setParams(params);
   BasicCookieStore localBasicCookieStore = new BasicCookieStore();
   client.setCookieStore(localBasicCookieStore);
 }
Ejemplo n.º 25
0
 private JSONObject Get(String url)
     throws ClientProtocolException, IOException, IllegalStateException, JSONException {
   HttpGet req = new HttpGet(url);
   HttpParams params = new BasicHttpParams();
   params.setParameter("http.protocol.handle-redirects", false);
   req.setParams(params);
   HttpResponse response = client.execute(req);
   JSONObject result = new JSONObject(convertToString(response.getEntity().getContent()));
   return result;
 }
Ejemplo n.º 26
0
  public RestResponse execute(HttpRequestBase request, RestResponse restResponse) {
    if (restResponse == null) restResponse = new RestResponse();

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, Timeout);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgent);
    DefaultHttpClient client = new DefaultHttpClient(params);
    client.setCookieStore(cookieJar);

    try {
      logCallDetails(request);
      HttpResponse response = client.execute(request);
      restResponse.setResponse(response);
    } catch (ClientProtocolException e) {
      restResponse.setException(e);
    } catch (IOException e) {
      restResponse.setException(e);
    }

    return restResponse;
  }
Ejemplo n.º 27
0
 /**
  * 创建HttpClient对象
  *
  * @return
  */
 public static HttpClient buildHttpClient() {
   try {
     SSLContext sslcontext = SSLContext.getInstance("TLS");
     sslcontext.init(null, new TrustManager[] {tm}, null);
     SSLSocketFactory ssf = new SSLSocketFactory(sslcontext);
     ClientConnectionManager ccm = new DefaultHttpClient().getConnectionManager();
     SchemeRegistry sr = ccm.getSchemeRegistry();
     sr.register(new Scheme("https", 443, ssf));
     HttpParams params = new BasicHttpParams();
     params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 8000);
     params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 8000);
     HttpClient httpclient = new DefaultHttpClient(ccm, params);
     httpclient
         .getParams()
         .setParameter(
             HTTP.USER_AGENT,
             "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)");
     return httpclient;
   } catch (Exception e) {
     throw new IllegalStateException(e);
   }
 }
Ejemplo n.º 28
0
  private HttpResponse makeRequest(String url, String username, String password)
      throws ClientProtocolException, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, new ProtocolVersion("HTTP", 1, 0));

    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);

    HttpGet httpget = new HttpGet(url);
    if (username != null && password != null) {
      httpget.setHeader(
          "Authorization",
          "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT));
    }
    return httpclient.execute(httpget);
  }
Ejemplo n.º 29
0
  @Override
  protected AbstractHttpClient createHttpClient() {
    AbstractHttpClient client = super.createHttpClient();
    try {

      if (ipAddress != null) {
        HttpParams params = client.getParams();
        params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(ipAddress));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return client;
  }
  @Override
  public String sendRequest() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient httpclient = new DefaultHttpClient(params);
    HttpPost httppost = new HttpPost(getUrl());
    BufferedReader in = null;
    String answer = "EmptyResponse";
    try {
      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      for (Map.Entry<String, String> pair : getParams().entrySet()) {
        nameValuePairs.add(new BasicNameValuePair(pair.getKey(), pair.getValue()));
      }
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      StringBuffer sb = new StringBuffer("");
      String line = "";
      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();
      String page = sb.toString();
      Logger.global.info(page);
      setResponse(page);
      return page;
    } catch (Exception e) {
      e.printStackTrace();
      answer = (e.getMessage() + "::" + e.getLocalizedMessage() + "::" + e.getCause());
      for (StackTraceElement stackTrace : e.getStackTrace()) {
        answer += "::" + stackTrace.toString();
      }
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return answer;
  }