コード例 #1
0
ファイル: Test.java プロジェクト: satyampatro/learning
  @SuppressWarnings("deprecation")
  public static void main(String[] args)
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
          KeyManagementException, UnrecoverableKeyException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      FileInputStream fis =
          new FileInputStream("/home/gauravabbi/official/issues/cipherIssue/testHttpsKS");
      try {
        trustStore.load(fis, "password".toCharArray());
      } finally {
        try {
          fis.close();
        } catch (Exception e) {
          System.err.println(e.getStackTrace());
        }
      }

      SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);

      Scheme scheme = new Scheme("https", 443, sslSocketFactory);
      httpclient.getConnectionManager().getSchemeRegistry().register(scheme);

      HttpGet getCall = new HttpGet("https://10.11.20.98:52080/test");
      HttpResponse response = httpclient.execute(getCall);

      System.out.println(response);
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }
コード例 #2
0
  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;
  }
コード例 #3
0
ファイル: Util.java プロジェクト: Aberstin/MusicMan
 /** 关闭Http的连接 */
 public static void shutDownHttpClient() {
   logger.v("shutDownHttpClient() ---> Enter");
   if (mHttpsClient != null) {
     mHttpsClient.getConnectionManager().shutdown();
     mHttpsClient = null;
   }
   if (mHttpClient != null) {
     mHttpClient.getConnectionManager().shutdown();
     mHttpClient = null;
   }
   logger.v(
       (new StringBuilder("shutDownHttpClient() ---> Exit, mHttpsClient = "))
           .append(mHttpsClient)
           .toString());
 }
コード例 #4
0
  /**
   * 客户签到提交数据
   *
   * @param token
   * @param uuid
   * @param imageLengthArray 图片大小 例如:13242314
   * @param pic 图片数据
   * @return 成功JsonPack.re=200
   * @throws Exception
   */
  public JsonPack PostUserSign_SC(
      String token, // 用户token
      String uuid, // task的uuid
      String imageLengthList, // 表示图片大小
      InputStream pic // 图片数据, //见方法说明
      ) throws Exception {

    DefaultHttpClient client = null;
    try {
      client = AbstractHttpApi.createHttpClientForUpload();
      HttpPost httpPost =
          mHttpApi.createHttpPost(
              fullUrl(URL_API_POST_Sign),
              pic,
              new BasicNameValuePair("token", token),
              new BasicNameValuePair("imageLengthList", imageLengthList),
              new BasicNameValuePair("uuid", uuid));
      JsonPack jsonPack = mHttpApi.doHttpRequest(httpPost);
      return jsonPack;
    } catch (Exception e) {
      throw e;
    } finally {
      if (client != null) {
        try {
          client.getConnectionManager().shutdown();
        } catch (Exception e) {

        }
      }
    }
  }
コード例 #5
0
 public void abort() {
   if (readyState > READY_STATE_UNSENT && readyState < READY_STATE_DONE) {
     if (client != null) {
       if (DBG) {
         Log.d(LCAT, "Calling shutdown on clientConnectionManager");
       }
       aborted = true;
       if (handler != null) {
         handler.client = null;
         if (handler.is != null) {
           try {
             if (handler.entity.isStreaming()) {
               handler.entity.consumeContent();
             }
             handler.is.close();
           } catch (IOException e) {
             Log.i(LCAT, "Force closing HTTP content input stream", e);
           } finally {
             handler.is = null;
           }
         }
       }
       if (client != null) {
         client.getConnectionManager().shutdown();
         client = null;
       }
     }
   }
 }
コード例 #6
0
  private void putUrlFile(String url, DefaultHttpClient httpClient, String content)
      throws NotFoundException, ReportableError {
    try {
      HttpPut httpPut = new HttpPut(url);
      httpPut.setEntity(new StringEntity(content, "UTF-8"));
      HttpResponse response = httpClient.execute(httpPut);
      StatusLine statResp = response.getStatusLine();
      int statCode = statResp.getStatusCode();
      if (statCode >= 400) {
        this.pushedStageFile = false;
        throw new ReportableError(
            r.getString(
                R.string.error_url_put_detail,
                url,
                "Server returned code: " + Integer.toString(statCode)),
            null);
      } else {
        this.pushedStageFile = true;
      }

      httpClient.getConnectionManager().shutdown();
    } catch (UnsupportedEncodingException e) {
      throw new ReportableError(
          r.getString(R.string.error_unsupported_encoding, "mobileorg.org"), e);
    } catch (IOException e) {
      throw new ReportableError(r.getString(R.string.error_url_put, url), e);
    }
  }
コード例 #7
0
ファイル: OSI.java プロジェクト: ash2005/Sec2
  /** httpGet */
  public static String httpGet(final String exist, String database, String android_id)
      throws IOException, HttpHostConnectException, ConnectException {
    String getUrl = "http://" + exist + ":50001/exist/rest/db/calendar/" + android_id + ".xml";
    LogHelper.logV(c, "httpGet: " + getUrl);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager ccm = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();

    httpClient =
        new DefaultHttpClient(
            new ThreadSafeClientConnManager(params, ccm.getSchemeRegistry()), params);
    httpClient.setRedirectHandler(new DefaultRedirectHandler());

    HttpGet get = new HttpGet(getUrl);

    get.setHeader("Location", database + ":50082");
    get.setHeader("Connection", "close");

    HttpResponse response = httpClient.execute(get);

    HttpEntity httpEntity = response.getEntity();

    return EntityUtils.toString(httpEntity);
  }
コード例 #8
0
ファイル: Subscriptions.java プロジェクト: ebmajor/reader
  /**
   * This method queries Google Reader for the list of subscribed feeds.
   *
   * @param sid authentication code to pass along in a cookie.
   * @return arr returns a JSONArray of JSONObjects for each feed.
   *     <p>The JSONObject returned by the service looks like this: id: this is the feed url. title:
   *     this is the title of the feed. sortid: this has not been figured out yet. firstitemsec:
   *     this has not been figured out yet.
   */
  public static JSONArray getSubscriptionList(String sid) {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpGet get = new HttpGet(SUB_URL + "/list?output=json");
    final BasicClientCookie cookie = Authentication.buildCookie(sid);

    try {
      client.getCookieStore().addCookie(cookie);

      final HttpResponse response = client.execute(get);
      final HttpEntity respEntity = response.getEntity();

      Log.d(TAG, "Response from server: " + response.getStatusLine());

      final InputStream in = respEntity.getContent();
      final BufferedReader reader = new BufferedReader(new InputStreamReader(in));

      String line = "";
      String arr = "";
      while ((line = reader.readLine()) != null) {
        arr += line;
      }

      final JSONObject obj = new JSONObject(arr);
      final JSONArray array = obj.getJSONArray("subscriptions");

      reader.close();
      client.getConnectionManager().shutdown();

      return array;
    } catch (final Exception e) {
      Log.d(TAG, "Exception caught:: " + e.toString());
      return null;
    }
  }
コード例 #9
0
  @Override
  protected ArrayList<RouteChangesEntity> doInBackground(Void... arg0) {

    ArrayList<RouteChangesEntity> routeChangesList;
    DefaultHttpClient routeChangesHttpClient = new DefaultHttpClient();

    try {
      StringBuilder htmlResult = new StringBuilder("");
      for (int page = 0; page < 5; page++) {
        HttpPost routeChangesHttpRequest = createRouteChangesRequest(page);
        htmlResult.append(routeChangesHttpClient.execute(routeChangesHttpRequest, responseHandler));
      }

      ProcessRouteChanges processRouteChanges = new ProcessRouteChanges(htmlResult.toString());
      routeChangesList = processRouteChanges.getRouteChangesList();
    } catch (Exception e) {
      routeChangesList = null;
    } finally {
      routeChangesHttpClient.getConnectionManager().shutdown();
    }

    // In case the progress dialog is dismissed - cancel the async task
    if (loadType == LoadTypeEnum.INIT && !progressDialog.isShowing()) {
      cancel(true);
    }

    return routeChangesList;
  }
 @AfterMethod
 public void tearDown() throws Exception {
   _memcached.shutdown();
   _tomcat1.stop();
   _httpClient.getConnectionManager().shutdown();
   _daemon.stop();
 }
コード例 #11
0
    public static synchronized DefaultHttpClient getThreadSafeClient() {

      if (clientThreadSafe != null) return clientThreadSafe;

      clientThreadSafe = new DefaultHttpClient();

      ClientConnectionManager mgr = clientThreadSafe.getConnectionManager();

      HttpParams params = clientThreadSafe.getParams();

      // timeout
      // int timeoutConnection = 25000;
      int timeoutConnection = 10000;
      HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);
      // int timeoutSocket = 25000;
      int timeoutSocket = 10000;
      HttpConnectionParams.setSoTimeout(params, timeoutSocket);
      clientThreadSafe =
          new DefaultHttpClient(
              new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);

      // disable requery
      clientThreadSafe.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
      // persistent cookies
      clientThreadSafe.setCookieStore(SmartLibMU.getCookieStore());

      return clientThreadSafe;
    }
コード例 #12
0
ファイル: BookUtil.java プロジェクト: kino1134/BookRemainder
  /**
   * 本情報を検索して、JSON文字列を取得する
   *
   * @param isbn
   * @return
   */
  private static String getJsonString(String isbn) {
    String result = null;

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(SearchUrl + SearchPath + isbn.trim());

    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(method);
      entity = response.getEntity();
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      method.abort();
      e.printStackTrace();
    } catch (IOException e) {
      method.abort();
      e.printStackTrace();
    } finally {
      try {
        if (entity != null) {
          entity.consumeContent();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.getConnectionManager().shutdown();

    return result;
  }
コード例 #13
0
ファイル: BookUtil.java プロジェクト: kino1134/BookRemainder
  /**
   * 画像取得するために、画像URLを渡して、バイト配列を取得する。 一応、画像じゃなくても取得は可能だと思われる。
   *
   * @param url
   * @return
   */
  public static byte[] getImage(String url) {
    byte[] result = new byte[0];

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(url);

    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(method);
      entity = response.getEntity();
      result = EntityUtils.toByteArray(entity);
    } catch (ClientProtocolException e) {
      method.abort();
      e.printStackTrace();
    } catch (IOException e) {
      method.abort();
      e.printStackTrace();
    } finally {
      try {
        if (entity != null) {
          entity.consumeContent();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.getConnectionManager().shutdown();

    return result;
  }
コード例 #14
0
  public JsonPack postArrival(
      String token, // 用户token
      String uuid, // task的uuid
      String imageLengthList, // 表示图片大小的数组(可支持多张图片)用分号分隔的方式依次存放了各图片的字节数。例如:13242314;29282
      InputStream pic // 图片数据, //见方法说明
      ) throws Exception {

    DefaultHttpClient client = null;
    try {
      client = AbstractHttpApi.createHttpClientForUpload();
      HttpPost httpPost =
          mHttpApi.createHttpPost(
              fullUrl(URL_API_POST_ARRIVAL),
              pic,
              new BasicNameValuePair("token", token),
              new BasicNameValuePair("imageLengthList", imageLengthList),
              new BasicNameValuePair("uuid", uuid));
      JsonPack jsonPack = mHttpApi.doHttpRequest(httpPost);
      return jsonPack;
    } catch (Exception e) {
      throw e;
    } finally {
      if (client != null) {
        try {
          client.getConnectionManager().shutdown();
        } catch (Exception e) {

        }
      }
    }
  }
コード例 #15
0
  /** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
コード例 #16
0
  @Override
  public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient
        .getParams()
        .setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
      httpClient
          .getCredentialsProvider()
          .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    }

    return httpClient;
  }
コード例 #17
0
  private static HttpClient createHttpClient(
      String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {
      schemeRegistry.register(
          new Scheme(
              "https",
              443,
              new SSLSocketFactory(
                  new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                      return true;
                    }
                  },
                  new AllowAllHostnameVerifier())));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
  }
コード例 #18
0
  @Override
  public void insertOrUpdatePreferences(EasitApplicationPreferences preferences, EasitAccount user)
      throws Exception {

    // Convert the prefs to
    String strPrefs = localPrefsToServerPrefs(preferences);

    // Prepare request and send it
    DefaultHttpClient client = new DefaultHttpClient();
    StringEntity input = new StringEntity(strPrefs);
    input.setContentEncoding("UTF8");
    input.setContentType("application/json");

    HttpPost postRequest =
        new HttpPost(
            environment.getProperty("flowManager.url") + "/oldpreferences/" + user.getUserToken());
    postRequest.setEntity(input);
    HttpResponse response = client.execute(postRequest);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      logger.info("ERROR:");
      logger.info(
          "URL target"
              + environment.getProperty("flowManager.url")
              + "/oldpreferences/"
              + user.getUserToken());
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Clear connection
    client.getConnectionManager().shutdown();
  }
コード例 #19
0
  // 获得用户首页的信息,返回MainPageInfoDTO
  // 如果没有数据更新,MainPageInfoDTO.needUpdateTag=false
  public JsonPack getMainPageInfo(
      String token, // 用户token
      long timestamp // 每次回传上次接收到的MainPageInfoDTO里的timestamp
          ,
      String latitude,
      String longitude,
      String acquisition_at)
      throws Exception {
    DefaultHttpClient client = null;
    try {
      client = AbstractHttpApi.createHttpClient();
      HttpPost httpGet =
          mHttpApi.createHttpPost(
              fullUrl(URL_API_GET_MAIN_PAGE_INFO),
              new BasicNameValuePair("token", token),
              new BasicNameValuePair("latitide", latitude),
              new BasicNameValuePair("longitude", longitude),
              new BasicNameValuePair("acquisition_at", acquisition_at));
      JsonPack jsonPack = mHttpApi.doHttpRequest(client, httpGet);

      return jsonPack;
    } catch (Exception e) {
      JsonPack jsonPack = new JsonPack();
      jsonPack.setRe(-1);
      return jsonPack;
    } finally {
      if (client != null) {
        try {
          client.getConnectionManager().shutdown();
        } catch (Exception e) {

        }
      }
    }
  }
コード例 #20
0
 protected final String invoke_put_string(String url, Bundle params) throws IOException {
   DefaultHttpClient dhc = new DefaultHttpClient();
   try {
     set_basic_auth(dhc);
     Log.i(_module_name, "PUT: " + url);
     HttpPut put = new HttpPut(url);
     sign_auth(put);
     if (params != null) {
       ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>();
       for (String key : params.keySet()) {
         nvps.add(new BasicNameValuePair(key, params.getString(key)));
       }
       UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
       put.setEntity(reqEntity);
     }
     HttpResponse httpResponse = dhc.execute(put);
     int statusCode = httpResponse.getStatusLine().getStatusCode();
     String res = UHttpComponents.loadStringFromHttpResponse(httpResponse);
     if (!is_ok_status(statusCode)) {
       String phrase = httpResponse.getStatusLine().getReasonPhrase();
       String msg = String.format("PUT*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url);
       throw new HttpIOException(msg, put, statusCode, phrase, res);
     }
     Log.i(_module_name, String.format("PUT-OK: %s <= %s", make_log_message(res.toString()), url));
     return res;
   } catch (IOException e) {
     Log.w(_module_name, String.format("PUT*IO: %s <= %s", e.getMessage(), url), e);
     throw e;
   } catch (Throwable e) {
     Log.w(_module_name, String.format("PUT*Throwable: %s <= %s", e.getMessage(), url), e);
     throw new InvocationTargetIOException(e);
   } finally {
     dhc.getConnectionManager().shutdown();
   }
 }
コード例 #21
0
  public String queryStation(
      Context context, Handler uiHandler, String stationCode, VechileType type) {
    // XXX do not create client every time, use HTTP1.1 keep-alive!
    final DefaultHttpClient client = new DefaultHttpClient();

    loadCookiesFromPreferences(context, client);
    // Create a response handler
    String result = null;
    try {
      do {
        final HttpPost request =
            createRequest(context, uiHandler, client, stationCode, previousResponse, type);
        result = client.execute(request, new BasicResponseHandler());
        previousResponse = result;
        saveCookiesToPreferences(context, client);
      } while (!result.contains(HAS_RESULT) && !result.contains(NO_INFO));

      if (result.contains(NO_INFO)) {
        result = context.getResources().getString(error_retrieveEstimates_matching_noInfo);
      }

    } catch (Exception e) {
      Log.e(TAG, "Could not get data for station " + stationCode, e);
    } finally {
      // XXX do not create client every time, use HTTP1.1 keep-alive!
      client.getConnectionManager().shutdown();
    }

    return result;
  }
コード例 #22
0
 protected final String invoke_delete_string(String url) throws IOException {
   DefaultHttpClient dhc = new DefaultHttpClient();
   try {
     set_basic_auth(dhc);
     Log.i(_module_name, "DELETE: " + url);
     HttpDelete delete = new HttpDelete(url);
     sign_auth(delete);
     HttpResponse httpResponse = dhc.execute(delete);
     int statusCode = httpResponse.getStatusLine().getStatusCode();
     String res = UHttpComponents.loadStringFromHttpResponse(httpResponse);
     if (!is_ok_status(statusCode)) {
       String phrase = httpResponse.getStatusLine().getReasonPhrase();
       String msg = String.format("DELETE*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url);
       throw new HttpIOException(msg, delete, statusCode, phrase, res);
     }
     Log.i(
         _module_name,
         String.format("DELETE-OK: %s <= %s", make_log_message(res.toString()), url));
     return res;
   } catch (IOException e) {
     Log.w(_module_name, String.format("DELETE*IO: %s <= %s", e.getMessage(), url), e);
     throw e;
   } catch (Throwable e) {
     Log.w(_module_name, String.format("DELETE*Throwable: %s <= %s", e.getMessage(), url), e);
     throw new InvocationTargetIOException(e);
   } finally {
     dhc.getConnectionManager().shutdown();
   }
 }
コード例 #23
0
  public boolean closeProject(User u, Date d, JFrame frame) { // sends end time for last open entry
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;
    this.endDate = new Timestamp(d.getTime());

    DefaultHttpClient client = u.getClient();
    HttpPost post = new HttpPost("http://" + Methodes.getIp() + "/webservice/closeProject");
    try {

      StringEntity create =
          new StringEntity("{\"end\":\"" + endDate + "\",\"pid\":\"" + id + "\"}");

      create.setContentType("application/json");
      post.setEntity(create);

      HttpResponse response = client.execute(post);
      BufferedReader rd =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
        check = true;
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
コード例 #24
0
 protected final JSONObject invoke_get_json(String url) throws IOException {
   DefaultHttpClient dhc = new DefaultHttpClient();
   try {
     set_basic_auth(dhc);
     Log.i(_module_name, "GET: " + url);
     HttpGet get = new HttpGet(url);
     sign_auth(get);
     HttpResponse httpResponse = dhc.execute(get);
     int statusCode = httpResponse.getStatusLine().getStatusCode();
     String res = UHttpComponents.loadStringFromHttpResponse(httpResponse);
     if (!is_ok_status(statusCode)) {
       String phrase = httpResponse.getStatusLine().getReasonPhrase();
       String msg = String.format("GET*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url);
       throw new HttpIOException(msg, get, statusCode, phrase, res);
     }
     Log.i(_module_name, String.format("GET-OK: %s <= %s", make_log_message(res), url));
     return new JSONObject(res);
   } catch (JSONException e) {
     Log.w(_module_name, String.format("GET*JSON: %s <= %s", e.getMessage(), url), e);
     throw new IOException(e.getMessage());
   } catch (IOException e) {
     Log.w(_module_name, String.format("GET*IO: %s <= %s", e.getMessage(), url), e);
     throw e;
   } catch (Throwable e) {
     Log.w(_module_name, String.format("GET*Throwable: %s <= %s", e.getMessage(), url), e);
     throw new InvocationTargetIOException(e);
   } finally {
     dhc.getConnectionManager().shutdown();
   }
 }
コード例 #25
0
  public boolean removeUser(User u, User remove, JFrame frame) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;
    users.add(remove);
    DefaultHttpClient client = u.getClient();
    HttpPost post = new HttpPost("http://" + Methodes.getIp() + "/webservice/removeProjectUser");
    try {
      // projectname, client ,summary
      StringEntity create =
          new StringEntity(
              "{\"pid\":\"" + id + "\",\"username\":\"" + remove.getUsername() + "\"}");
      create.setContentType("/application/json");
      post.setEntity(create);
      System.out.println("{\"pid\":\"" + id + "\",\"username\":\"" + remove.getUsername() + "\"}");
      HttpResponse response = client.execute(post);
      BufferedReader rd =
          new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
        check = removeUser(remove.getUsername());
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
コード例 #26
0
ファイル: FinalHttp.java プロジェクト: newisso/afinal
  public static Bitmap downloadBitmap(String url) {
    DefaultHttpClient client = getDefaultHttpClient(null);
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          inputStream = entity.getContent();
          final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
          return bitmap;
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      getRequest.abort();
    } finally {
      if (client != null) {
        client.getConnectionManager().shutdown();
      }
    }
    return null;
  }
コード例 #27
0
ファイル: GReader.java プロジェクト: shangrz/FlipDroid
  public void requestToken() throws ParseException, HttpException, IOException {
    if (!this.isGetSidAndAuth) return;
    String url = "https://www.google.com/reader/api/0/token?client=scroll&ck=";

    // HttpClient httpclient = new DefaultHttpClient();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String timestap = String.valueOf(getTimestamp());
    HttpGet get = new HttpGet(url + timestap);
    get.setHeader("Authorization", "GoogleLogin auth=" + auth);
    get.setHeader("Cookie", "SID=" + sid);
    HttpResponse response = null;
    response = httpclient.execute(get);
    int result = response.getStatusLine().getStatusCode();
    ////// System.out.println(result);
    if (result == 200) {
      // this.token = get.getResponseBodyAsString().substring(2);
      //// System.out.println("2222222222222");
      this.token = EntityUtils.toString(response.getEntity()).substring(2);
      //// System.out.println(this.token);
    }
    // ////System.out.println(this.token);
    get.abort();
    httpclient.getConnectionManager().shutdown();
    httpclient = null;
  }
コード例 #28
0
  public boolean getEntries(User u, JFrame frame) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;

    DefaultHttpClient client = u.getClient();
    HttpGet getRequest =
        new HttpGet("http://" + Methodes.getIp() + "/webservice/getProjectById/" + id);
    try {
      HttpResponse resp = client.execute(getRequest);
      // Date start, Date end, String description,Project p
      BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
      String output = "";
      boolean oneLoop = true;
      while ((output = rd.readLine()) != null) {
        if (oneLoop) {
          Synchronisatie.setOfflineEntries(this.id, output, this.user.username);
        }
        oneLoop = false;
        System.out.println(output);
        JSONObject jsonObject = new JSONObject(output);
        JSONArray array = jsonObject.optJSONArray("entries");
        for (int i = 0; i < array.length(); i++) {
          JSONObject entry = (JSONObject) array.get(i);
          String description = entry.getString("notities");
          String name = entry.getString("achternaam");
          String firstname = entry.getString("voornaam");

          String begin = entry.getString("begin");
          String eind = entry.getString("eind");

          System.out.println(eind);

          Date start = Timestamp.valueOf(begin);
          Date end;
          if (eind.equals("0000-00-00 00:00:00")) {
            end = null;
          } else {

            end = Timestamp.valueOf(eind);
          }
          int uid = entry.getInt("uid");
          String trid = entry.getString("trid");
          // int rid = entry.getInt("rid");
          if (entries.add(new Entry(start, end, description, u, this.id, trid))) check = true;
          // System.out.println(new Entry(start,end,description,this,new User(uid,firstname,name)));

        }
      }

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
コード例 #29
0
ファイル: ConvoidApp.java プロジェクト: Pewpewarrows/Convoid
  private HttpClient createHttpClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();

    return new DefaultHttpClient(
        new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
  }
コード例 #30
0
 public HttpClientFactory() {
   httpClient = new DefaultHttpClient(getClientConnectionManager());
   httpClient.setParams(getHttpParams());
   gridClient = new DefaultHttpClient(getClientConnectionManager());
   gridClient.setRedirectStrategy(new MyRedirectHandler());
   gridClient.setParams(getGridHttpParams());
   gridClient.getConnectionManager().closeIdleConnections(100, TimeUnit.MILLISECONDS);
 }