/** * 获取网络图片 * * @param url * @return */ public static Bitmap getBitmapByNet(String url) throws AppException { // System.out.println("image_url==> "+url); URI uri = null; try { uri = new URI(url, false, "UTF-8"); } catch (URIException e) { e.printStackTrace(); } if (uri != null) url = uri.toString(); HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; int time = 0; do { try { httpClient = HttpHelper.getHttpClient(); httpGet = HttpHelper.getHttpGet(url, HttpHelper.getUserAgent()); int statusCode = httpClient.executeMethod(httpGet); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生网络异常 e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpGet.releaseConnection(); } } while (time < RETRY_TIME); return bitmap; }
@Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.info("Executing job"); httpHelper = new HttpHelper(); try { JSONObject nodesStats = httpHelper.getJsonFromUrl("http://localhost:9200/_nodes/stats?all"); JSONObject clusterStats = httpHelper.getJsonFromUrl("http://localhost:9200/_cluster/stats"); putStats(nodesStats, clusterStats); } catch (Exception e) { logger.error("Error during getting stats", e); } }
@Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. if (checkPlayServices()) { try { // Get authentication key HttpHelper http = new HttpHelper(this.mEmail, this.mPassword, 7000); HttpResultHelper httpResult = http.post(SERVER_URL + IOPUSH_URL_GET_AUTH_TOKEN, null, null); BufferedReader in = new BufferedReader(new InputStreamReader(httpResult.getResponse())); String result = ""; String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } if (httpResult.getStatusCode() == 200) { JSONObject credentials = new JSONObject(result); String nickname = credentials.getString("nickname"); String authToken = credentials.getString("authToken"); SharedPreferences userSharedPref = getApplicationContext() .getSharedPreferences(getString(R.string.preferenceUser), Context.MODE_PRIVATE); userSharedPref .edit() .putString(getString(R.string.preferenceUserNickname), nickname) .apply(); userSharedPref .edit() .putString(getString(R.string.preferenceUserAuthToken), authToken) .apply(); Log.d(TAG, "Auth token retrieved"); return true; } else if (httpResult.getStatusCode() == 401) { Log.i(TAG, "Wrong credentials."); return false; } else { Log.i(TAG, "Failed to get auth_token, error code : " + httpResult.getStatusCode()); Log.i(TAG, "Error message : " + result); } } catch (Exception e) { Log.d(TAG, "Failed to register", e); } } else { Log.i(TAG, "No internet connection"); } // Return false by default return false; }
private static String generatePayPalNonce(BraintreeGateway gateway, QueryString payload) { String encodedClientToken = gateway.clientToken().generate(); String clientToken = TestHelper.decodeClientToken(encodedClientToken); String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); Configuration configuration = gateway.getConfiguration(); String url = configuration.getBaseURL() + configuration.getMerchantPath() + "/client_api/v1/payment_methods/paypal_accounts"; payload .append("authorization_fingerprint", authorizationFingerprint) .append("shared_customer_identifier_type", "testing") .append("shared_customer_identifier", "test-identifier") .append("paypal_account[options][validate]", "false"); String responseBody; String nonce = ""; try { responseBody = HttpHelper.post(url, payload.toString()); nonce = extractParamFromJson("nonce", responseBody); } catch (Exception e) { throw new RuntimeException(e); } return nonce; }
public static String generateNonceForCreditCard( BraintreeGateway gateway, CreditCardRequest creditCardRequest, String customerId, boolean validate) { ClientTokenRequest clientTokenRequest = new ClientTokenRequest().customerId(customerId); String encodedClientToken = gateway.clientToken().generate(clientTokenRequest); String clientToken = TestHelper.decodeClientToken(encodedClientToken); String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); Configuration configuration = gateway.getConfiguration(); String url = configuration.getBaseURL() + configuration.getMerchantPath() + "/client_api/v1/payment_methods/credit_cards"; QueryString payload = new QueryString(); payload .append("authorization_fingerprint", authorizationFingerprint) .append("shared_customer_identifier_type", "testing") .append("shared_customer_identifier", "fake_identifier") .append("credit_card[options][validate]", new Boolean(validate).toString()); String responseBody; String nonce = ""; try { String payloadString = payload.toString(); payloadString += "&" + creditCardRequest.toQueryString(); responseBody = HttpHelper.post(url, payloadString); nonce = extractParamFromJson("nonce", responseBody); } catch (Exception e) { throw new RuntimeException(e); } return nonce; }
public static String generateUnlockedNonce( BraintreeGateway gateway, String customerId, String creditCardNumber) { ClientTokenRequest request = new ClientTokenRequest(); if (customerId != null) { request = request.customerId(customerId); } String encodedClientToken = gateway.clientToken().generate(request); String clientToken = TestHelper.decodeClientToken(encodedClientToken); String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); Configuration configuration = gateway.getConfiguration(); String url = configuration.getBaseURL() + configuration.getMerchantPath() + "/client_api/nonces.json"; QueryString payload = new QueryString(); payload .append("authorization_fingerprint", authorizationFingerprint) .append("shared_customer_identifier_type", "testing") .append("shared_customer_identifier", "test-identifier") .append("credit_card[number]", creditCardNumber) .append("credit_card[expiration_month]", "11") .append("share", "true") .append("credit_card[expiration_year]", "2099"); String responseBody; String nonce = ""; try { responseBody = HttpHelper.post(url, payload.toString()); nonce = extractParamFromJson("nonce", responseBody); } catch (Exception e) { throw new RuntimeException(e); } return nonce; }
public void onSave(View view) { HttpHelper.setUnified(mChkIsUnified.isChecked()); Manager.Instance.saveRegistration( mEditClientId.getText().toString(), mEditRedirectUri.getText().toString()); final Intent intent = new Intent(getApplicationContext(), ConnectActivity.class); startActivity(intent); }
public BookmarkCollection GetAll() throws Exception { EntityType et = EntityType.GetEntityType(Bookmark.class); // run... String url = GetServiceUrl(et); Document doc = HttpHelper.DownloadXml(url, GetDownloadSettings()); // load... return (BookmarkCollection) LoadEntities(doc, et); }
@Test public void downloadRemoteResource() throws IOException { String filePath = System.getProperty("user.dir") + "/test.txt"; String returnedFilePath = HttpHelper.downloadRemoteResource(filePath, "http://localhost:8080/download/test.txt"); Assert.assertTrue(filePath.equals(returnedFilePath)); File file = new File(filePath); BufferedReader reader = new BufferedReader(new FileReader(file)); String text = reader.readLine().trim(); reader.close(); Assert.assertTrue(text.equals("hello")); Assert.assertTrue(file.delete()); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mEditClientId = (EditText) findViewById(R.id.clientId); mEditRedirectUri = (EditText) findViewById(R.id.redirectUri); mEditClientId.setText(Manager.Instance.getClientId()); mEditRedirectUri.setText(Manager.Instance.getRedirectUri()); mChkIsUnified = (CheckBox) findViewById(R.id.isUnified); mChkIsUnified.setChecked(HttpHelper.isUnified()); }
public static String sendRequestPost(String URL) throws UnsupportedEncodingException { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(URL); request.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response; String responseStr; try { response = client.execute(request); responseStr = HttpHelper.request(response); return responseStr; } catch (Exception e) { Log.i(Constants.TAG, "não foi possivel mandar post"); } return null; }
/* Twilio.InitListener method */ @Override public void onInitialized() { Log.v(LOGTAG, "Twilio SDK is Initialized"); try { Log.v(LOGTAG, "Auth URL: " + appContext.getString(R.string.twilio_auth_url)); String capabilityToken = HttpHelper.httpGet(appContext.getString(R.string.twilio_auth_url)); Log.v( LOGTAG, appContext.getString(R.string.twilio_auth_url) + " Auth Token: " + capabilityToken); device = Twilio.createDevice(capabilityToken, null /* DeviceListener */); Log.v(LOGTAG, "Created Twilio Device"); } catch (Exception e) { Log.e(LOGTAG, "Failed to obtain capability token: " + e.toString()); } }
public static String sendRequestGet(String URL) throws UnsupportedEncodingException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); HttpResponse response; String responseStr; try { response = client.execute(request); responseStr = HttpHelper.request(response); return responseStr; } catch (Exception e) { Log.i(Constants.TAG, "não foi possivel mandar get"); Log.e(Constants.TAG, e.getMessage(), e); } return null; }
private void getCapabilityToken(String url, PendingIntent intent) { this.capabilityToken = null; this.device = null; try { this.pendingIntent = intent; this.capabilityToken = HttpHelper.httpGet(url); this.device = Twilio.createDevice(this.capabilityToken, null); Log.d(TAG, this.capabilityToken); if (this.pendingIntent != null) { Log.d(TAG, "setting pending intent"); device.setIncomingIntent(pendingIntent); } else { Log.d(TAG, "incoming call unavailable"); } } catch (Exception e) { Log.e(TAG, "Failed to obtain capability token: " + e.getLocalizedMessage()); } }
public static String generateEuropeBankAccountNonce(BraintreeGateway gateway, Customer customer) { SEPAClientTokenRequest request = new SEPAClientTokenRequest(); request.customerId(customer.getId()); request.mandateType(EuropeBankAccount.MandateType.BUSINESS); request.mandateAcceptanceLocation("Rostock, Germany"); String encodedClientToken = gateway.clientToken().generate(request); String clientToken = TestHelper.decodeClientToken(encodedClientToken); String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); Configuration configuration = gateway.getConfiguration(); String url = configuration.getBaseURL() + configuration.getMerchantPath() + "/client_api/v1/sepa_mandates"; QueryString payload = new QueryString(); payload .append("authorization_fingerprint", authorizationFingerprint) .append("sepa_mandate[locale]", "de-DE") .append("sepa_mandate[bic]", "DEUTDEFF") .append("sepa_mandate[iban]", "DE89370400440532013000") .append("sepa_mandate[accountHolderName]", "Bob Holder") .append("sepa_mandate[billingAddress][streetAddress]", "123 Currywurst Way") .append("sepa_mandate[billingAddress][extendedAddress]", "Lager Suite") .append("sepa_mandate[billingAddress][firstName]", "Wilhelm") .append("sepa_mandate[billingAddress][lastName]", "Dix") .append("sepa_mandate[billingAddress][locality]", "Frankfurt") .append("sepa_mandate[billingAddress][postalCode]", "60001") .append("sepa_mandate[billingAddress][countryCodeAlpha2]", "DE") .append("sepa_mandate[billingAddress][region]", "Hesse"); String responseBody; String nonce = ""; try { responseBody = HttpHelper.post(url, payload.toString()); nonce = extractParamFromJson("nonce", responseBody); } catch (Exception e) { throw new RuntimeException(e); } return nonce; }
private void putStats(JSONObject nodesStats, JSONObject clusterStats) throws IOException { String indexName = IndexNameFactory.getIndexName(); StringBuilder sb = new StringBuilder(); if (nodesStats.has("nodes")) { JSONObject nodes = nodesStats.getJSONObject("nodes"); for (String key : (Set<String>) nodes.keySet()) { JSONObject node_data = nodes.getJSONObject(key); if (node_data.has("name")) { String nodeName = node_data.getString("name"); JSONObject nodeData = new JSONObject(); nodeData.put("_index", indexName); nodeData.put("_type", nodeName); JSONObject metadata = new JSONObject(); metadata.put("index", nodeData); sb.append(metadata); sb.append('\n'); sb.append(node_data.toString()); sb.append('\n'); } } } JSONObject clusterData = new JSONObject(); clusterData.put("_index", indexName); clusterData.put("_type", "cluster"); JSONObject metadata = new JSONObject(); metadata.put("index", clusterData); sb.append(metadata); sb.append('\n'); sb.append(clusterStats.toString()); sb.append('\n'); httpHelper.postString("http://localhost:9200/_bulk", sb.toString()); }
@Override public UsageStats getUsageStats() { Map<String, Object> objectMap = HttpHelper.getUrlContentAsMap(getStatsUrl(), httpClient); Long total_preferences = 0l; Object preferences = objectMap.get("total_preferences"); if (preferences instanceof Long) { total_preferences = (Long) preferences; } else if (preferences instanceof String) { total_preferences = Long.parseLong((String) preferences); } else if (preferences instanceof Double) { total_preferences = ((Double) preferences).longValue(); } Object keys = objectMap.get("distinct_keys"); Long distinct_keys = 0l; if (keys instanceof Long) { distinct_keys = (Long) keys; } else if (preferences instanceof String) { distinct_keys = Long.parseLong((String) keys); } else if (preferences instanceof Double) { distinct_keys = ((Double) keys).longValue(); } return new UsageStats(distinct_keys, total_preferences); }
@Override public void updateSettings(Map<String, Object> settingsMap) { HttpHelper.postContentWithBodyAndGetResult( getSettingsUrl(), gson.toJson(settingsMap), httpClient); }
public String post(String operation) { return httpHelper.doPost(host + URL, operation); }
/** * This method simulates a call to a page so all castor caches fills up before we throw the old * page cache. * * @param db * @param siteNodeId * @param languageId * @param contentId */ public void recache(DatabaseWrapper dbWrapper, Integer siteNodeId) throws SystemException, Exception { logger.info("recache starting.."); HttpHelper helper = new HttpHelper(); String recacheUrl = CmsPropertyHandler.getRecacheUrl() + "?siteNodeId=" + siteNodeId + "&refresh=true&isRecacheCall=true"; String response = helper.getUrlContent(recacheUrl, 30000); String recacheBaseUrl = CmsPropertyHandler.getRecacheUrl().replaceAll("/ViewPage.action", ""); String pathsToRecacheOnPublishing = CmsPropertyHandler.getPathsToRecacheOnPublishing(); if (pathsToRecacheOnPublishing.indexOf("pathsToRecacheOnPublishing") == -1) { String[] pathsToRecacheOnPublishingArray = pathsToRecacheOnPublishing.split(","); for (int i = 0; i < pathsToRecacheOnPublishingArray.length; i++) { recacheUrl = recacheBaseUrl + pathsToRecacheOnPublishingArray[i] + "?refresh=true&isRecacheCall=true"; logger.info("calling recacheUrl:" + recacheUrl); } } LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController() .getMasterLanguageForSiteNode(dbWrapper.getDatabase(), siteNodeId); if (masterLanguageVO == null) throw new SystemException("There was no master language for the siteNode " + siteNodeId); Integer languageId = masterLanguageVO.getLanguageId(); if (languageId == null) languageId = masterLanguageVO.getLanguageId(); Integer contentId = new Integer(-1); Principal principal = (Principal) CacheController.getCachedObject("userCache", "anonymous"); if (principal == null) { Map arguments = new HashMap(); arguments.put("j_username", CmsPropertyHandler.getAnonymousUser()); arguments.put("j_password", CmsPropertyHandler.getAnonymousPassword()); principal = ExtranetController.getController() .getAuthenticatedPrincipal(dbWrapper.getDatabase(), arguments); if (principal != null) CacheController.cacheObject("userCache", "anonymous", principal); } FakeHttpSession fakeHttpServletSession = new FakeHttpSession(); FakeHttpServletResponse fakeHttpServletResponse = new FakeHttpServletResponse(); FakeHttpServletRequest fakeHttpServletRequest = new FakeHttpServletRequest(); fakeHttpServletRequest.setParameter("siteNodeId", "" + siteNodeId); fakeHttpServletRequest.setParameter("languageId", "" + languageId); fakeHttpServletRequest.setParameter("contentId", "" + contentId); fakeHttpServletRequest.setRequestURI("ViewPage.action"); fakeHttpServletRequest.setAttribute("siteNodeId", "" + siteNodeId); fakeHttpServletRequest.setAttribute("languageId", "" + languageId); fakeHttpServletRequest.setAttribute("contentId", "" + contentId); fakeHttpServletRequest.setServletContext(DeliverContextListener.getServletContext()); BrowserBean browserBean = new BrowserBean(); // this.browserBean.setRequest(getRequest()); NodeDeliveryController nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(siteNodeId, languageId, contentId); IntegrationDeliveryController integrationDeliveryController = IntegrationDeliveryController.getIntegrationDeliveryController( siteNodeId, languageId, contentId); TemplateController templateController = getTemplateController( dbWrapper, siteNodeId, languageId, contentId, new FakeHttpServletRequest(), (InfoGluePrincipal) principal, false, browserBean, nodeDeliveryController, integrationDeliveryController); DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(/*(InfoGluePrincipal)this.principal*/ ); // deliveryContext.setRepositoryName(repositoryName); deliveryContext.setSiteNodeId(siteNodeId); deliveryContext.setContentId(contentId); deliveryContext.setLanguageId(languageId); deliveryContext.setPageKey("" + System.currentTimeMillis()); // deliveryContext.setSession(new Session(fakeHttpServletSession)); // deliveryContext.setInfoGlueAbstractAction(null); deliveryContext.setHttpServletRequest(fakeHttpServletRequest); deliveryContext.setHttpServletResponse(fakeHttpServletResponse); templateController.setDeliveryContext(deliveryContext); // We don't want a page cache entry to be created deliveryContext.setDisablePageCache(true); SiteNodeVO siteNodeVO = templateController.getSiteNode(siteNodeId); SiteNodeVO rootSiteNodeVO = templateController.getRepositoryRootSiteNode(siteNodeVO.getRepositoryId()); recurseSiteNodeTree( rootSiteNodeVO.getId(), languageId, templateController, principal /*, dbWrapper*/, 1, 0); List templates = ContentController.getContentController() .getContentVOWithContentTypeDefinition("HTMLTemplate", dbWrapper.getDatabase()); Iterator templatesIterator = templates.iterator(); { ContentVO template = (ContentVO) templatesIterator.next(); String templateString = templateController.getContentAttribute(template.getId(), languageId, "Template", true); } RepositoryVO repository = RepositoryDeliveryController.getRepositoryDeliveryController() .getMasterRepository(dbWrapper.getDatabase()); RepositoryDeliveryController.getRepositoryDeliveryController() .getRepositoryVOListFromServerName( dbWrapper.getDatabase(), "localhost", "8080", repository.getName()); logger.info("recache stopped.."); }
@Override public void bulkUpdatePreferences(InputStream in) { logger.debug("Start posting bulk update..."); HttpHelper.postContentWithBodyAndGetResult(getBulkUpdateUrl(), in, httpClient); logger.debug("Bulk update finished..."); }
@Override public void deleteAllPreferences() { logger.debug("Deleting All preferences!"); HttpHelper.deleteContent(getDeleteAllPreferencesUrl(), httpClient); }
@Override public Map<String, Object> getSettings() { return HttpHelper.getUrlContentAsMap(getSettingsUrl(), httpClient); }
@Override public Map<String, Object> getRecommendation(long userID) { return HttpHelper.getUrlContentAsMap(getRecommendationUrl(userID), httpClient); }
@Override public String getAllPreferences() { return HttpHelper.getUrlContent(getDeleteAllPreferencesUrl(), httpClient); }
@Override public void createPreference(long userID, long itemID, float preference) { HttpHelper.postContentWithBodyAndGetResult( getPreferenceUrl(userID, itemID, preference), EMPTY_CONTENT, httpClient); }
@Override public void deletePreferencesOfUser(long userID) { logger.debug("Deleting All preferences of user {}", userID); HttpHelper.deleteContent(getDeleteSpecificUsersPreferencesUrl(userID), httpClient); }