List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Checks if is passed.//from w ww .j a v a 2s. c o m * * @param endPoint the end point * @param testId the test id * @param client the client (optional) * @return the string * @throws Exception */ public static String isPassed(String endPoint, String testId, CloseableHttpClient client) throws Exception { if (testId == null) { throw new Exception(""); } boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); try { return jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns") .getJSONObject("TestRun").getString("status"); } catch (JSONException e) { return null; } } else if (response.getStatusLine().getStatusCode() == 404) { throw new NotFoundException("Test not found"); } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress"); } } catch (Exception e) { Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e); throw e; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } return null; }
From source file:org.hfoss.posit.web.Communicator.java
/** * Sends a HttpPost request to the given URL. Any JSON * @param Uri the URL to send to/receive from * @param sendMap the hashMap of data to send to the server as POST data * @return the response from the URL/*ww w . j a va2 s . c o m*/ */ private String doHTTPPost(String Uri, HashMap<String, String> sendMap) { if (Uri == null) throw new NullPointerException("The URL has to be passed"); String responseString = null; HttpPost post = new HttpPost(); if (Utils.debug) Log.i(TAG, "doHTTPPost() URI = " + Uri); try { post.setURI(new URI(Uri)); } catch (URISyntaxException e) { Log.e(TAG, "URISyntaxException " + e.getMessage()); e.printStackTrace(); return e.getMessage(); } List<NameValuePair> nvp = PositHttpUtils.getNameValuePairs(sendMap); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { post.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncodingException " + e.getMessage()); } mStart = System.currentTimeMillis(); try { responseString = mHttpClient.execute(post, responseHandler); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolExcpetion" + e.getMessage()); e.printStackTrace(); return e.getMessage(); } catch (IOException e) { Log.e(TAG, "IOException " + e.getMessage()); e.printStackTrace(); return e.getMessage(); } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException: " + e.getMessage()); e.printStackTrace(); return e.getMessage(); } catch (Exception e) { Log.e(TAG, "Exception on HttpPost " + e.getMessage()); e.printStackTrace(); return e.getMessage(); } long time = System.currentTimeMillis() - mStart; mTotalTime += time; Log.i(TAG, "TIME = " + time + " millisecs"); return responseString; }
From source file:dataServer.StorageRESTClientManager.java
public boolean deleteKPIStorage(String kpiID) { // Default HTTP response and common properties for responses HttpResponse response = null;/* www. ja va2s . c o m*/ ResponseHandler<String> handler = null; int status = 0; String body = null; try { HttpDelete query = new HttpDelete(StreamPipes.concat("/").concat(kpiID)); System.out.println( "\n\n\n########################################################################################################\n\n\n"); System.out.println(query.toString()); System.out.println( "\n\n\n########################################################################################################\n\n\n"); response = client.execute(query); System.out.println("\n\n\nResponse:\n" + response.toString()); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { //throw new RuntimeException("Failed! HTTP error code: " + status); //keep the kpi in de DB System.out.println("Error accessing storage: " + status); return false; } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); //result return true; } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); return false; } }
From source file:com.josephblough.sbt.transport.SbaTransport.java
private static List<RecommendedSite> getRecommendedSites(final String url) { try {/*from www . j av a 2s. co m*/ HttpClient client = new DefaultHttpClient(); Log.d(TAG, "url: " + url); HttpGet httpMethod = new HttpGet(url); ResponseHandler<String> handler = new BasicResponseHandler(); String response = client.execute(httpMethod, handler); JSONArray array = new JSONArray(response); return processRecommendedSites(array); } catch (OutOfMemoryError e) { return null; } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public boolean websericeR4WContacts() { String contacts_returned = "", r4wName = "", r4wUserImage = "", r4wstatus = ""; System.out.println("getAllContacts:" + getAllContacts.length); HttpParams p = new BasicHttpParams(); p.setParameter("user", "1"); HttpClient httpclient = new DefaultHttpClient(p); String url = "http://ip.roaming4world.com/esstel/fetch_contacts_file.php?" + "self_contact=" + selfNumber; HttpPost httppost = new HttpPost(url); System.out.println("URL being sent is " + url); try {//ww w. ja v a 2s.c o m Log.i(getClass().getSimpleName(), "send task - start"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("user", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("Response Body is " + responseBody); // Parse JSONObject jsonObjRecv; try { JSONArray jsonArray = null; jsonObjRecv = new JSONObject(responseBody); Log.d(TAG, "jsonObjRecv :" + jsonObjRecv); String contacts = jsonObjRecv.getString("contacts"); if (contacts.equals("Error") || contacts.equals("No Contacts")) { Log.d(TAG, "No contacts Error"); prefs.edit().putString(signUpProcess, "R4wContactInserted").commit(); } else { jsonArray = jsonObjRecv.getJSONArray("contacts"); String path = jsonObjRecv.getString("path"); Log.d(TAG, "jsonArray :" + jsonArray + "path:" + path); if (jsonArray.length() != 0) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject position = jsonArray.getJSONObject(i); contacts_returned += position.getString("p") + ","; r4wName += position.getString("un") + ","; r4wstatus += position.getString("s") + ","; String url_image = position.getString("t"); if (!url_image.equals("No image")) { r4wUserImage += path + url + ","; } else { r4wUserImage += position.getString("t") + ","; } if (jsonArray.getString(i) == "") { } } System.out.println("data=:contacts_returned :r4wName:r4wstatus :r4wUserImage" + contacts_returned + ":" + r4wName + ":" + r4wstatus + "" + r4wUserImage + ""); System.out.println(); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //return true; } catch (UnknownHostException e) { e.printStackTrace(); return false; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (Exception e) { //e.printStackTrace(); return false; } if (contacts_returned.length() != 0) { contacts_returned = contacts_returned.substring(0, contacts_returned.length() - 1); r4wName = r4wName.substring(0, r4wName.length() - 1); r4wstatus = r4wstatus.substring(0, r4wstatus.length() - 1); r4wUserImage = r4wUserImage.substring(0, r4wUserImage.length() - 1); contact_array = contacts_returned.split(","); r4wNameArray = r4wName.split(","); r4wUserStatus = r4wstatus.split(","); r4wUserImageArray = r4wUserImage.split(","); RContactlist.r4wCompleteContactList = new String[contact_array.length]; com.roamprocess1.roaming4world.api.Roaming4WorldCustomApi.r4wContacts = contact_array; for (int i = 0; i < com.roamprocess1.roaming4world.api.Roaming4WorldCustomApi.r4wContacts.length; i++) { String number = com.roamprocess1.roaming4world.api.Roaming4WorldCustomApi.r4wContacts[i]; //System.out.println("number :"+number); int index = r4wContactListName.indexOf(number.trim()); //System.out.println("index ="+index); try { if (index != -1) { System.out.println("index =" + index); String r4wContactName = allContactsPhone[index]; String[] parts = r4wContactName.split(","); String r4wNamePhone = parts[0]; String r4wNumberName = parts[1]; String datacomplte = r4wNamePhone + "," + r4wNumberName + "," + r4wUserStatus[i] + "," + r4wUserImageArray[i] + "," + r4wNameArray[i]; System.out.println("datacomplte-" + datacomplte); RContactlist.r4wCompleteContactList[i] = datacomplte; } } catch (Exception e) { // TODO: handle exception } } System.out.println("r4wCompleteContactList.length:" + RContactlist.r4wCompleteContactList.length); } else { System.out.println("No Contact"); } return true; }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
/** * This method is use to post data in multidata format * @param url//from w w w. j a v a 2 s . c om * - backend url * @param mobileApplicationBean * - Bean class of the mobile application * @param headers * - header files */ public static String doPostMultiData(String url, MobileApplicationBean mobileApplicationBean, Map<String, String> headers) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // initializing headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); httpPost.setHeader(key, headers.get(key)); } } MultipartEntityBuilder reqEntity; reqEntity = MultipartEntityBuilder.create(); reqEntity.addPart("version", new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("provider", new StringBody(mobileApplicationBean.getProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("markettype", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("platform", new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("description", new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA)); FileBody bannerImageFile = new FileBody(mobileApplicationBean.getBannerFilePath()); reqEntity.addPart("bannerFile", bannerImageFile); FileBody iconImageFile = new FileBody(mobileApplicationBean.getIconFile()); reqEntity.addPart("iconFile", iconImageFile); FileBody screenShot1 = new FileBody(mobileApplicationBean.getScreenShot1File()); reqEntity.addPart("screenshot1File", screenShot1); FileBody screenShot2 = new FileBody(mobileApplicationBean.getScreenShot2File()); reqEntity.addPart("screenshot2File", screenShot2); FileBody screenShot3 = new FileBody(mobileApplicationBean.getScreenShot3File()); reqEntity.addPart("screenshot3File", screenShot3); reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("mobileapp", new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("sso_ssoProvider", new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("appmeta", new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA)); final HttpEntity entity = reqEntity.build(); httpPost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; try { responseBody = httpClient.execute(httpPost, responseHandler); } catch (Exception e) { e.printStackTrace(); } return responseBody; }
From source file:com.yayandroid.utility.MapHelperFragment.java
/** * GoogleApis returns an address as jsonObject according to given * coordinate, and here we parse it to find necessary fields *///w w w .j ava 2 s . co m private void fetchInformationUsingGoogleMap() { final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient .newInstance(MapHelperFragment.class.getName()); String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + myLocation.getLatitude() + "," + myLocation.getLongitude() + "&sensor=false&language=tr"; try { JSONObject googleMapResponse = new JSONObject( ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl), new BasicResponseHandler())); // many nested loops.. not great -> use expression instead // loop among all results JSONArray results = (JSONArray) googleMapResponse.get("results"); for (int i = 0; i < results.length(); i++) { // loop among all addresses within this result JSONObject result = results.getJSONObject(i); if (result.has("address_components")) { JSONArray addressComponents = result.getJSONArray("address_components"); for (int j = 0; j < addressComponents.length(); j++) { JSONObject addressComponent = addressComponents.getJSONObject(j); if (result.has("types")) { JSONArray types = addressComponent.getJSONArray("types"); for (int k = 0; k < requiredInformations.length; k++) { for (int l = 0; l < types.length(); l++) { if (requiredInformations[k].type.value.equals(types.getString(l))) { if (addressComponent.has("long_name")) { PostInformation(requiredInformations[k].type, addressComponent.getString("long_name")); } else if (addressComponent.has("short_name")) { PostInformation(requiredInformations[k].type, addressComponent.getString("short_name")); } } } } } } } } } catch (Exception ignored) { ignored.printStackTrace(); } ANDROID_HTTP_CLIENT.close(); }
From source file:com.comcast.dawg.pound.DawgPoundIT.java
/** * This method tests the @link{DawgPound#unreserve()} API with invalid id , and verifies the * response./* w w w . j ava 2 s . c o m*/ */ @Test(groups = "rest") public void unreserveWithInvalidIdTest() throws ClientProtocolException, IOException { String url = BASE_URL + "unreserve/" + invalidDeviceId; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); Assert.assertNotNull(responseBody); Assert.assertTrue(responseBody.isEmpty()); }
From source file:io.cos.cas.authentication.handler.support.OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java
/** * Securely notify the OSF of a Remote Principal Authentication credential. Allows the OSF the opportunity * to create a verified user account and/or assign institutional affiliation to the user's account. * * @param credential the credential object bearing the authentication headers from the idp * @return the username from the idp and setup on the OSF * @throws AccountException a account exception */// w ww.j a va 2s .com private PrincipalAuthenticationResult notifyRemotePrincipalAuthenticated( final OpenScienceFrameworkCredential credential) throws AccountException { try { final JSONObject normalized = this.normalizeRemotePrincipal(credential); final JSONObject provider = normalized.getJSONObject("provider"); final String institutionId = provider.getString("id"); final String username = provider.getJSONObject("user").getString("username"); final String payload = normalized.toString(); logger.info("Notify Remote Principal Authenticated: username={}, institution={}", username, institutionId); logger.debug("Notify Remote Principal Authenticated [{}, {}] Normalized Payload '{}'", username, institutionId, payload); // Build a JWT and wrap it with JWE for secure transport to the OSF API. final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(username).claim("data", payload) .expirationTime(new Date(new Date().getTime() + SIXTY_SECONDS)).build(); final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet); final JWSSigner signer = new MACSigner(this.institutionsAuthJwtSecret.getBytes()); signedJWT.sign(signer); final JWEObject jweObject = new JWEObject( new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM).contentType("JWT").build(), new Payload(signedJWT)); jweObject.encrypt(new DirectEncrypter(this.institutionsAuthJweSecret.getBytes())); final String jweString = jweObject.serialize(); // A call is made to the OSF CAS Institution Login Endpoint to create a registered user (if // one does not already exist) and apply institutional affiliation. final HttpResponse httpResponse = Request.Post(this.institutionsAuthUrl) .addHeader(new BasicHeader("Content-Type", "text/plain")) .bodyString(jweString, ContentType.APPLICATION_JSON).execute().returnResponse(); final int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.info("Notify Remote Principal Authenticated [OSF API] Response: <{}> Status Code {}", username, statusCode); // The institutional authentication endpoint should always respond with a 204 No Content when successful. if (statusCode != HttpStatus.SC_NO_CONTENT) { final String responseString = new BasicResponseHandler().handleResponse(httpResponse); logger.error("Notify Remote Principal Authenticated [OSF API] Response Body: '{}'", responseString); throw new RemoteUserFailedLoginException("Invalid Status Code from OSF API Endpoint"); } // return the username for the credential build. return new PrincipalAuthenticationResult(username, institutionId); } catch (final JOSEException | IOException | ParserConfigurationException | TransformerException e) { logger.error("Notify Remote Principal Authenticated Exception: {}", e.getMessage()); logger.trace("Notify Remote Principal Authenticated Exception: {}", e); throw new RemoteUserFailedLoginException("Unable to Build Message for OSF API Endpoint"); } }