public String notifyHunter(byte[] content) throws IOException { try { String request = new String(content); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection"); String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}"; StringEntity entity = new StringEntity(json); entity.setContentType("applicaiton/json"); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); String responseString = new BasicResponseHandler().handleResponse(response); return responseString; } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex); } return "Error Notifying Probe Server!"; }
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) { Optional<String> result = Optional.empty(); final int waitTime = 60000; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime) .setConnectionRequestTimeout(waitTime).build(); httpRequest.setConfig(requestConfig); result = Optional.of(client.execute(httpRequest, responseHandler)); } catch (HttpResponseException httpResponseException) { LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest, httpResponseException.getMessage()); } catch (IOException ioe) { LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage()); } finally { httpRequest.releaseConnection(); } return result; }
public AccessTokenDTO getToken(String code) { DefaultHttpClient httpclient = new DefaultHttpClient(); AccessTokenDTO token = null; try { HttpPost httppost = new HttpPost("https://api.twitch.tv/kraken/oauth2/token" + "?client_id=" + Config.getCatalog().twitch.clientId + "&client_secret=" + Config.getCatalog().twitch.clientSecret + "&code=" + code + "&grant_type=authorization_code" + "&redirect_uri=" + Config.getCatalog().twitch.redirectUri); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); token = new Gson().fromJson(responseBody, AccessTokenDTO.class); } catch (IOException e) { TwasiLogger.log.error(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); httpclient.close(); } return token; }
/** * 查询配置 */ public Map<String, String> queryConfig() { try { String resultStr = HTTP_CLIENT.execute(request, new BasicResponseHandler()); FindPropertiesResult result = JSON.parseObject(resultStr, FindPropertiesResult.class); if (result == null) { throw new RuntimeException("请求配置中心失败"); } if (!result.isSuccess()) { throw new RuntimeException("从配置中心读取配置失败:" + result.getMessage()); } return result.getProperties(); } catch (IOException e) { return ExceptionUtils.rethrow(e); } }
public static String getText(String redirectLocation) { HttpGet httpget = new HttpGet(redirectLocation); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; try { responseBody = httpclient.execute(httpget, responseHandler); } catch (Exception e) { e.printStackTrace(); responseBody = null; } finally { httpget.abort(); // httpclient.getConnectionManager().shutdown(); } return responseBody; }
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); System.out.println("----------------------------------------"); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
private JSONObject getResponseJsonObject(String httpMethod, String url, Object params) throws IOException, MtWmErrorException { HttpUriRequest httpUriRequest = null; String fullUrl = getBaseApiUrl() + url; List<NameValuePair> sysNameValuePairs = getSysNameValuePairs(fullUrl, params); List<NameValuePair> nameValuePairs = getNameValuePairs(params); if (HTTP_METHOD_GET.equals(httpMethod)) { sysNameValuePairs.addAll(nameValuePairs); HttpGet httpGet = new HttpGet(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8)); setRequestConfig(httpGet); httpUriRequest = httpGet; } else if (HTTP_METHOD_POST.equals(httpMethod)) { HttpPost httpPost = new HttpPost(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, UTF_8)); setRequestConfig(httpPost); httpUriRequest = httpPost; } CloseableHttpResponse response = this.httpClient.execute(httpUriRequest); String resultContent = new BasicResponseHandler().handleResponse(response); JSONObject jsonObject = JSON.parseObject(resultContent); MtWmError error = MtWmError.fromJson(jsonObject); if (error != null) { logging(url, httpMethod, false, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent); throw new MtWmErrorException(error.getErrorCode(), error.getErrorMsg()); } logging(url, httpMethod, true, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent); return jsonObject; }
private static String makeBasicPostRequest(String path, JSONObject jsonObject, String token) throws Exception { DefaultHttpClient httpclient = getNewHttpClient(); HttpPost httpPost = new HttpPost(path); StringEntity se = new StringEntity(jsonObject.toString()); httpPost.setEntity(se); setBasicHeaders(httpPost, token); //Handles what is returned from the page ResponseHandler responseHandler = new BasicResponseHandler(); String response = "{\"success\":\"false\"}"; try { response = (String) httpclient.execute(httpPost, responseHandler); } catch (org.apache.http.client.HttpResponseException e) { e.printStackTrace(); // todo: retrieve status code and evaluate it Log.d("statusCode order Post", Integer.toString(e.getStatusCode())); } return response; }
/** * Send HTTP POST request to {@link #getEndpointUrl(), imports impex * * @param file * file to be imported * @return import status message * @throws IOException * @throws HttpResponseException */ private String postImpex(final IFile file) throws HttpResponseException, IOException { final Map<String, String> parameters = new HashMap<>(); final HttpPost postRequest = new HttpPost(getEndpointUrl() + ImpexImport.IMPEX_IMPORT_PATH); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(getTimeout()).build(); parameters.put(ImpexImport.Parameters.ENCODING, getEncoding()); parameters.put(ImpexImport.Parameters.SCRIPT_CONTENT, getContentOfFile(file)); parameters.put(ImpexImport.Parameters.MAX_THREADS, ImpexImport.Parameters.MAX_THREADS_VALUE); parameters.put(ImpexImport.Parameters.VALIDATION_ENUM, ImpexImport.Parameters.VALIDATION_ENUM_VALUE); postRequest.setConfig(requestConfig); postRequest.addHeader(getxCsrfToken(), getCsrfToken()); postRequest.setEntity(new UrlEncodedFormEntity(createParametersList(parameters))); final HttpResponse response = getHttpClient().execute(postRequest, getContext()); final String responseBody = new BasicResponseHandler().handleResponse(response); return getImportStatus(responseBody); }
/** * Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken} * token * * @return true if {@link #endpointUrl} is accessible * @throws IOException * @throws ClientProtocolException * @throws AuthenticationException */ protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException { final HttpGet getRequest = new HttpGet(getEndpointUrl()); try { final HttpResponse response = httpClient.execute(getRequest, getContext()); final String responseString = new BasicResponseHandler().handleResponse(response); csrfToken = getCsrfToken(responseString); if( StringUtil.isBlank(csrfToken) ) { throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED); } } catch (UnknownHostException error) { final String errorMessage = error.getMessage(); final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl()); if (matcher.find() && matcher.group(1).equals(errorMessage)) { throw new UnknownHostException( String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1))); } throw error; } }
public static void updateExternalIPAddr() { nu_log.i("Retrieving external IP address."); CloseableHttpClient cli = HttpClients.createDefault(); nu_log.d("IP retrieval URL = " + ip_retrieval_url); HttpGet req = new HttpGet(ip_retrieval_url); req.addHeader("User-Agent", "PacChat HTTP " + Main.VERSION); try { CloseableHttpResponse res = cli.execute(req); BasicResponseHandler handler = new BasicResponseHandler(); external_ip = handler.handleResponse(res); nu_log.i("External IP address detected as: " + external_ip); } catch (IOException e) { nu_log.e("Error while retrieving external IP!"); e.printStackTrace(); } }
public String getResponseByPost(String url,String encode,String[] params)throws Exception{ httpPost = new HttpPost(url); List<org.apache.http.NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>(); for(int i=0; i<params.length/2;i++){ formParams.add(new BasicNameValuePair(params[i*2], params[i*2+1])); } HttpEntity entityForm = new UrlEncodedFormEntity(formParams, encode); httpPost.setEntity(entityForm); ResponseHandler<String> responseHandler = new BasicResponseHandler(); content = httpClient.execute(httpPost, responseHandler); return content; }
public String getResponseByProxy(String url)throws Exception{ httpClient = new DefaultHttpClient(); do{ HttpHost proxy = new HttpHost((String)getProxy().get(0), (Integer)getProxy().get(1)); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpGet = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); int count = 0; try{ content = httpClient.execute(httpGet, responseHandler); }catch(Exception e){ System.out.println("Remote accessed by proxy["+(String)getProxy().get(0)+":"+(Integer)getProxy().get(1)+"] had Error!Try next!"); } count++; if(count>2){break;} }while(content.length()==0); return content; }
private void postLine(String data) throws Exception { StringEntity postingString = new StringEntity(data); //System.out.println(data); httpPost.setEntity(postingString); //httpPost.setHeader("Content-type","plain/text"); httpPost.setHeader("Content-type", "application/json"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String resp = httpClient.execute(httpPost, responseHandler); //JSONObject jsonResp = new JSONObject(resp); //System.out.println(jsonResp); httpPost.releaseConnection(); }
private String getText(String redirectLocation) { HttpGet httpget = new HttpGet(redirectLocation); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; try { responseBody = httpclient.execute(httpget, responseHandler); } catch (Exception e) { e.printStackTrace(); responseBody = null; } finally { httpget.abort(); httpclient.getConnectionManager().shutdown(); } return responseBody; }
@Override protected BookObject doInBackground(String... isbn) { String url = baseURL + isbn[0]; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = httpclient.execute(httpget, responseHandler); Log.d("Response", response); JSONObject jsonObject = new JSONObject(response); bookObject = new BookObject(); bookObject.setAuthor(jsonObject.getString("authors")); bookObject.setCategory(jsonObject.getString("category")); bookObject.setImage(jsonObject.getString("image")); bookObject.setIsbn(jsonObject.getString("isbn")); bookObject.setPublisher(jsonObject.getString("publisher")); bookObject.setRating(jsonObject.getString("rating")); bookObject.setSummary(jsonObject.getString("summary")); bookObject.setTitle(jsonObject.getString("title")); } catch (Exception e){ e.printStackTrace(); } return bookObject; }
static <T extends SparkResponse> T executeHttpMethodAndGetResponse(HttpClient client, HttpRequestBase httpRequest, Class<T> responseClass) throws FailedSparkRequestException { T response; try { final String stringResponse = client.execute(httpRequest, new BasicResponseHandler()); if (stringResponse != null) { response = MapperWrapper.MAPPER.readValue(stringResponse, responseClass); } else { throw new FailedSparkRequestException("Received empty string response"); } } catch (IOException e) { throw new FailedSparkRequestException(e); } finally { httpRequest.releaseConnection(); } if (response == null) { throw new FailedSparkRequestException("An issue occured with the cluster's response."); } return response; }
@Test public void testShouldHandlePostRequests() throws IOException { // Given a mock server configured to respond to a POST / with data // "Hello World" with an ID responseProvider.expect(Method.POST, "/", "text/plain; charset=UTF-8", "Hello World").respondWith(200, "text/plain", "ABCD1234"); // When a request for POST / arrives final HttpPost req = new HttpPost(baseUrl + "/"); req.setEntity(new StringEntity("Hello World", UTF_8)); final ResponseHandler<String> handler = new BasicResponseHandler(); final String responseBody = client.execute(req, handler); // Then the response is "ABCD1234" Assert.assertEquals("ABCD1234", responseBody); }
public final void run() { Process.setThreadPriority(10); try { synchronized (CLIENT) { String str = (String)CLIENT.execute(this.mRequest, new BasicResponseHandler()); this.mCallback.onSuccess(JsoMap.buildJsoMap(str)); return; } return; } catch (Exception localException) { this.mCallback.onFailure$786b7c60(); } }
public EsperIOHTTPSubscription(String stream, String uriWithReplacements) throws URISyntaxException, ConfigurationException { this.httpclient = new DefaultHttpClient(); this.responseHandler = new BasicResponseHandler(); this.stream = stream; if (uriWithReplacements.indexOf("${") == -1) { uriPrecompiled = new URI(uriWithReplacements); fragments = null; } else { try { fragments = PlaceholderParser.parsePlaceholder(uriWithReplacements); } catch (PlaceholderParseException e) { throw new ConfigurationException("URI with placeholders '" + uriWithReplacements + "' could not be parsed"); } uriPrecompiled = null; } }
/** * get请求 * * @param url 地址 * @param param 参数 * @return */ public static String get(String url, Map param) { if (!param.isEmpty()) { String ps = org.treeleaf.common.http.basic.Http.param2UrlParam(param); url += "?" + ps; } HttpGet httpget = new HttpGet(url); ResponseHandler responseHandler = new BasicResponseHandler(); try { return (String) httpClient_https.execute(httpget, responseHandler); } catch (IOException e) { throw new HttpException("调用" + url + "出错", e); } }
/** * Contacts ME3Tweaks and fetches the latest ASI mod info. */ public static boolean getOnlineASIManifest() { URIBuilder urib; String responseString = null; try { urib = new URIBuilder(ASI_MANIFEST_LINK); HttpClient httpClient = HttpClientBuilder.create().build(); URI uri = urib.build(); ModManager.debugLogger.writeMessage("Getting latest ASI mod manifest from link: " + uri.toASCIIString()); HttpResponse response = httpClient.execute(new HttpGet(uri)); responseString = new BasicResponseHandler().handleResponse(response); FileUtils.writeStringToFile(ModManager.getASIManifestFile(), responseString, StandardCharsets.UTF_8); ModManager.debugLogger.writeMessage("File written to disk. Exists on filesystem, ready for loading: " + ModManager.getASIManifestFile().exists()); return true; } catch (IOException | URISyntaxException e) { ModManager.debugLogger.writeErrorWithException("Error fetching latest asi mod manifest file:", e); if (ModManager.getASIManifestFile().exists()) { ModManager.debugLogger.writeError("The old manifest will be loaded."); } else { ModManager.debugLogger.writeError("No manifest exists locally. New ASIs will not be usable within Mod Manager."); } } return false; }
/** * This method tests the @link{DawgPound#listAll()} , and verifies the response body. * * @throws IOException * @throws ClientProtocolException */ @Test(groups = "rest") public void listAllTest() throws ClientProtocolException, IOException { String expectedStb2 = "00:00:00:00:00:AA"; addStb("0000000000aa", expectedStb2); String url = BASE_URL + "list"; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); Assert.assertNotNull(responseBody); Assert.assertTrue(responseBody.contains(mac)); Assert.assertTrue(responseBody.contains(expectedStb2)); }
/** * This method tests the @link{DawgPound#getReservered()} API with valid token, and verifies the * response body. * * @throws IOException * @throws ClientProtocolException */ @Test(groups = "rest") public void getReserveredTest() throws ClientProtocolException, IOException { String deviceId = MetaStbBuilder.getUID(UID_PREF); addStb(deviceId, mac); String token = "sathyv"; String expectedStr = "\"reserver_key\":\"" + token + "\""; int status = reserveTheBox(token, deviceId); Assert.assertEquals(status, 200, "Could not reserve the box."); String url = BASE_URL + "reserved/token/" + token; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); Assert.assertNotNull(responseBody, "While trying to get reserved status, response received is null."); Assert.assertTrue(responseBody.contains(expectedStr), String.format("Failed to find the reserver key(%s) in response(%s).", expectedStr, responseBody)); Assert.assertTrue(responseBody.contains(deviceId), String.format("Failed to find the device ID(%s) in response(%s).", deviceId, responseBody)); }
/** * This method tests the @link{DawgPound#reserve()} API with invalid id, and verifies that the * response is false. */ @Test(groups = "rest") public void reserveWithInvalidIdTest() throws ClientProtocolException, IOException { String token = "xyz"; long exp = System.currentTimeMillis() + RESERVE_EXPIRATION_TIME_OFFSET; String expiration = String.valueOf(exp); String url = BASE_URL + "reserve/override/" + token + "/" + invalidDeviceId + "/" + expiration; 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.contains("false")); }
/** * This method tests the @link{DawgPound#reserve()} API with invalid expiration, and verifies * that the response is false. */ @Test(groups = "rest") public void reserveWithInvalidExpirationTest() throws ClientProtocolException, IOException { String deviceId = MetaStbBuilder.getUID(UID_PREF); addStb(deviceId, mac); String token = "xyz"; long exp = System.currentTimeMillis() - RESERVE_EXPIRATION_TIME_OFFSET; String expiration = String.valueOf(exp); // less than current time String url = BASE_URL + "reserve/override/" + token + "/" + invalidDeviceId + "/" + expiration; 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.contains("false")); responseBody = isReserved(deviceId); Assert.assertTrue(!responseBody.contains(token)); }
/** * This method tests the @link{HouseRestController#add()} API with a valid id - * 'aabbccddeeff' */ @Test(groups="rest") public void addTest() { String id = "ffeeddccbbaa"; String mac = "FF:EE:DD:CC:BB:AA"; try { int statusCode = addStb(id, mac); Assert.assertEquals(statusCode, 200); // verify the response of getStbsById String url = TestServers.getHouse() + "devices/id/" + id; HttpGet method = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(method, responseHandler); Assert.assertNotNull(responseBody); Assert.assertTrue(responseBody.contains(mac)); } catch (Exception e) { Assert.fail("Caught exception " + e); } }
/** * This method tests the @link{HouseRestController#add()} addition of Stb's * with invalid model names and verifies that user given family and * capabilities gets populated * * @throws ClientProtocolException * @throws IOException */ @Test(dataProvider = "addStbWithInvalidModelParams") public void testAddStbWithInvalidModelName(String stbInitialCaps, String stbInitialFamily) throws ClientProtocolException, IOException { String modelName = "InvalidModel"; String id = MetaStbBuilder.getUID("modeltest"); String mac = "00:00:00:00:00:BB"; // Add stb with an invalid model name that doesn't exist int status = addStb(id, mac, modelName, stbInitialCaps, stbInitialFamily); Assert.assertTrue(status == HttpStatus.OK_200, "could not add the stb " + id + " with invalid model name"); HttpClient httpclient = new DefaultHttpClient(); String url = TestServers.getHouse() + "/devices/id/" + id; HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); Assert.assertNotNull(responseBody); Assert.assertTrue(responseBody.contains(modelName)); Assert.assertTrue(responseBody.contains(stbInitialCaps)); Assert.assertTrue(responseBody.contains(stbInitialFamily)); }
/** * This method tests the @link{HouseRestController#deleteSingle()} API with a valid random id * @throws IOException * @throws ClientProtocolException */ @Test(groups="rest") public void deleteSingleValidIdTest() throws ClientProtocolException, IOException { String id = MetaStbBuilder.getUID(ID_PREF); int status = addStb(id, MAC); Assert.assertTrue(status == HttpStatus.OK_200, "could not add the stb " + MAC); String url = TestServers.getHouse() + "devices/id/" + id; int statusCode = removeStb(id); Assert.assertEquals(statusCode, HttpStatus.OK_200); // verify that the box is deleted try { HttpGet httpGet = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); httpClient.execute(httpGet, responseHandler); Assert.fail("Did not throw exception for the removed stb"); } catch (Exception exp) { Assert.assertTrue(exp instanceof HttpResponseException); } }
/** * This method tests the @link{HouseRestController#getStbsByIds()} API with an invalid * param 'xyz' * @throws ClientProtocolException * @throws IOException */ @Test(groups="rest", expectedExceptions={HttpResponseException.class}) public void getStbsByIdsWithInvalidIdsTest() throws ClientProtocolException, IOException { String url = TestServers.getHouse() + "devices/id"; HttpPost method = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("id", "xyz")); method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(method, responseHandler); Assert.assertNotNull(responseBody); Assert.assertFalse(responseBody.contains("xyz")); }
/** * This method tests the @link{HouseRestController#getStbsByQuery()} API with a the given property * @throws ClientProtocolException * @throws IOException */ @Test(groups="rest") public void getStbsByQueryTest() throws ClientProtocolException, IOException { //add an stb with model 'newmodel' String model = "newmodel"; String id = "000000000000"; String url = TestServers.getHouse() + "devices/id/" + id; HttpEntity entity = new StringEntity("{\"model\":\"" + model +"\"}"); HttpPut method = new HttpPut(url); method.addHeader("Content-Type", "application/json"); method.setEntity(entity); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(method); //get the added stb url = TestServers.getHouse() + "devices/query?q=" + model; HttpGet httpGet = new HttpGet(url); httpClient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(httpGet, responseHandler); Assert.assertTrue(responseBody.contains(model)); }
@SuppressWarnings({"rawtypes", "unchecked"}) private void postDeviceStatus(String baseURL, DefaultHttpClient httpclient) throws Exception { String devicestatusURL = baseURL + "devicestatus"; Log.i(TAG, "devicestatusURL: " + devicestatusURL); JSONObject json = new JSONObject(); json.put("uploaderBattery", DexcomG4Activity.batLevel); String jsonString = json.toString(); HttpPost post = new HttpPost(devicestatusURL); StringEntity se = new StringEntity(jsonString); post.setEntity(se); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); ResponseHandler responseHandler = new BasicResponseHandler(); httpclient.execute(post, responseHandler); }
protected String doInBackground(Server... params) { passedServer = params[0]; String manifestUrl = passedServer.serverAddress + "/forumfiend.json"; if(checkURL(manifestUrl)) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(manifestUrl); httpget.setHeader("User-Agent", "ForumFiend"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); return responseBody; } catch(Exception ex) { } } return null; }
synchronized private Set<String> doLookup(long freshness) { String url = registryURL + "?freshness=" + freshness; try { HttpGet method = new HttpGet(url); ResponseHandler<String> handler = new BasicResponseHandler(); String response = httpClient.execute(method, handler); LOG.debug("GET to " + url + " got a " + response); Set<String> rc = new HashSet<String>(); Scanner scanner = new Scanner(response); while (scanner.hasNextLine()) { String service = scanner.nextLine(); if (service.trim().length() != 0) { rc.add(service); } } return rc; } catch (Exception e) { LOG.debug("GET to " + url + " failed with: " + e); return null; } }
@Override public boolean close() { logger.debug("Closing Client Session"); try { HttpUriRequest request = new HttpDelete(getServerURI(workspaceLocation.getServiceInfo(), "session/" + getWorkspace().getUUID())); outboundHttpClient.execute(request, new BasicResponseHandler()); } catch (Exception e) { try { logger.error(e); getContext().createUserPrompter("Cannot access the server to close the server session", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, UserPromptResponse.OK, "OK"); } catch (Throwable t) { //do nothing here because we failed on logging the error. } } outboundHttpClient.getConnectionManager().shutdown(); updater.interrupt(); if (dataSourceCollection != null) { dataSourceCollectionUpdater.detach(dataSourceCollection); } return super.close(); }
/** * List all the workspaces on this context's server. * * @param serviceInfo * @return * @throws IOException * @throws URISyntaxException * @throws JSONException */ public static List<WorkspaceLocation> getWorkspaceNames(SPServerInfo serviceInfo) throws IOException, URISyntaxException, JSONException { HttpClient httpClient = createHttpClient(serviceInfo); try { HttpUriRequest request = new HttpGet(getServerURI(serviceInfo, "workspaces")); String responseBody = httpClient.execute(request, new BasicResponseHandler()); JSONArray response; List<WorkspaceLocation> workspaces = new ArrayList<WorkspaceLocation>(); response = new JSONArray(responseBody); logger.debug("Workspace list:\n" + responseBody); for (int i = 0; i < response.length(); i++) { JSONObject workspace = (JSONObject) response.get(i); workspaces.add(new WorkspaceLocation( workspace.getString("name"), workspace.getString("UUID"), serviceInfo)); } return workspaces; } finally { httpClient.getConnectionManager().shutdown(); } }
/** * Sends an HTTP request to a Wabit Enterprise Server to create a new remote * Wabit Workspace on that server. * * @param serviceInfo * A {@link SPServerInfo} containing the connection * information for that server * @return The {@link WorkspaceLocation} of the newly created remote * WabitWorkspace * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException * @throws JSONException */ public static WorkspaceLocation createNewServerSession(SPServerInfo serviceInfo) throws URISyntaxException, ClientProtocolException, IOException, JSONException { HttpClient httpClient = createHttpClient(serviceInfo); try { HttpUriRequest request = new HttpPost(getServerURI(serviceInfo, "workspaces")); String responseBody = httpClient.execute(request, new BasicResponseHandler()); JSONObject response = new JSONObject(responseBody); logger.debug("New Workspace:" + responseBody); return new WorkspaceLocation( response.getString("name"), response.getString("UUID"), serviceInfo); } finally { httpClient.getConnectionManager().shutdown(); } }
public static String sendData(String urlex, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException{ httpclient=new DefaultHttpClient(); httppost= new HttpPost(URL_TELEGRAM+urlex); Log.d("MU","trying konek"); //httppost.setHeader(new BasicHeader("token", TOKEN)); //StringEntity entity = new StringEntity("token", "UTF-8"); //Log.d("MU","set entitas"); //httppost.setEntity(entity); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.d("MU","entiti value pairs was set"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return httpclient.execute(httppost,responseHandler); }
/** * @return the RAW XML document of ItemLookup (Large Response) from Amazon * product advertisement API * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws ClientProtocolException * @throws IOException */ public String getXMLLargeResponse() throws InvalidKeyException, NoSuchAlgorithmException, ClientProtocolException, IOException { String responseBody = ""; String signedurl = signInput(); try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(signedurl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); // responseBody now contains the contents of the page // System.out.println(responseBody); httpclient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Exception" + " " + itemID + " " + e.getClass()); } return responseBody; }