List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java
@Test(groups = "wso2.as", description = "Verfiy Spring Session scope") public void testSpringSessionScope() throws Exception { String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/session"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet(endpoint); HttpResponse response1 = httpClient.execute(httpget, httpContext); String responseMsg1 = new BasicResponseHandler().handleResponse(response1); HttpResponse response2 = httpClient.execute(httpget, httpContext); String responseMsg2 = new BasicResponseHandler().handleResponse(response2); httpClient.close();/* www .j a va2 s .co m*/ assertTrue(responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should be the same"); }
From source file:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java
synchronized private void doRegister(String service) { String url = registryURL;//w ww. jav a2 s . c om try { HttpPut method = new HttpPut(url); method.addHeader("service", service); ResponseHandler<String> handler = new BasicResponseHandler(); String responseBody = httpClient.execute(method, handler); LOG.debug("PUT to " + url + " got a " + responseBody); } catch (Exception e) { LOG.debug("PUT to " + url + " failed with: " + e); } }
From source file:com.cellobject.oikos.util.NetworkHelper.java
/** * Sends HTTP GET request and returns body of response from server as String *//*from w w w . j ava2 s . c om*/ public String httpGet(final String urlToServer) throws IOException { final HttpGet request = new HttpGet(urlToServer); final ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String responseBody = client.execute(request, responseHandler); return responseBody; }
From source file:com.amazon.advertising.api.sample.ItemLookupSample.java
private static void getItemInfo(String asin, SignedRequestsHelper helper) { DefaultHttpClient httpclient = new DefaultHttpClient(); Map<String, String> params = new HashMap<String, String>(); params.put("Service", "AWSECommerceService"); params.put("Version", "2011-08-01"); params.put("Operation", "ItemLookup"); params.put("ItemId", asin); params.put("ResponseGroup", "Images"); String requestUrl = helper.sign(params); System.out.println("Request is \"" + requestUrl + "\""); HttpGet httpGet = new HttpGet(requestUrl); String responseBody = ""; try {//from w w w. j a va 2s . c o m ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpGet, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(responseBody); }
From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java
private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException { mCancelable = false;// w ww.j a va 2 s . com if (!SafeSlinger.getApplication().isOnline()) { throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection)); } // sets up parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); if (mHttpClient == null) { mHttpClient = new CheckedHttpClient(params, mCtx); } HttpPost httppost = new HttpPost(uri); BasicResponseHandler responseHandler = new BasicResponseHandler(); byte[] reqData = null; HttpResponse response = null; long startTime = SystemClock.elapsedRealtime(); int statCode = 0; String statMsg = ""; String error = ""; try { // Execute HTTP Post Request httppost.addHeader("Content-Type", "application/octet-stream"); httppost.setEntity(new ByteArrayEntity(requestBody)); mTxTotalBytes = requestBody.length; final long totalTxBytes = TrafficStats.getTotalTxBytes(); final long totalRxBytes = TrafficStats.getTotalRxBytes(); if (totalTxBytes != TrafficStats.UNSUPPORTED) { mTxStartBytes = totalTxBytes; } if (totalRxBytes != TrafficStats.UNSUPPORTED) { mRxStartBytes = totalRxBytes; } response = mHttpClient.execute(httppost); reqData = responseHandler.handleResponse(response).getBytes("8859_1"); } catch (UnsupportedEncodingException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (HttpResponseException e) { // this subclass of java.io.IOException contains useful data for // users, do not swallow, handle properly statCode = e.getStatusCode(); statMsg = e.getLocalizedMessage(); error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'"); } catch (java.io.IOException e) { // just show a simple Internet connection error, so as not to // confuse users error = mCtx.getString(R.string.error_CorrectYourInternetConnection); } catch (RuntimeException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (OutOfMemoryError e) { error = mCtx.getString(R.string.error_OutOfMemoryError); } finally { long msDelta = SystemClock.elapsedRealtime() - startTime; if (response != null) { StatusLine status = response.getStatusLine(); if (status != null) { statCode = status.getStatusCode(); statMsg = status.getReasonPhrase(); } } MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0) + "b recv, " + statCode + " code, " + msDelta + "ms"); } if (!TextUtils.isEmpty(error) || reqData == null) { throw new ExchangeException(error); } return reqData; }
From source file:co.tuzza.swipehq.transport.ManagedHttpTransport.java
@Override public <T> T doPost(String url, Map<String, String> params, Class<T> c) throws Exception { HttpUriRequest method;//from w ww . j a va 2s. c o m HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(parseParams(params), "UTF-8")); method = httpPost; HttpClient client = getHttpClient(); HttpResponse httpResponse = client.execute(method); String response = new BasicResponseHandler().handleResponse(httpResponse); return ResponseParser.parseResponse(response, c); }
From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java
/** * Test of create method, of class VehicleController. * * @throws java.io.IOException// w w w . j a v a 2 s . c om */ @Test public void testCreate() throws IOException { System.out.println("create"); Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); String testVehicleString = objectMapper.writeValueAsString(testVehicle); // System.out.println(testVehicleString); StringEntity postEntity = new StringEntity(testVehicleString, ContentType.create("application/json", "UTF-8")); postEntity.setChunked(true); // System.out.println(postEntity.getContentType()); // System.out.println(postEntity.getContentLength()); // System.out.println(EntityUtils.toString(postEntity)); // System.out.println(EntityUtils.toByteArray(postEntity).length); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles"); httppost.setEntity(postEntity); CloseableHttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); assertEquals(parseMongoId(responseString), true); }
From source file:com.redblackit.war.X509HttpClientTest.java
/** * Do request and validate response//from ww w . j a va2 s.co m * * @param httpClientToTest * @param url * @param expectedTitle */ private void validateResponseToRequest(HttpClient httpClientToTest, String url, String expectedTitle) throws Exception { HttpGet request = new HttpGet(url); HttpResponse response = httpClientToTest.execute(request); logger.info("request:" + request); StatusLine status = response.getStatusLine(); Assert.assertEquals("Status code:" + status, HttpStatus.SC_OK, status.getStatusCode()); logger.info(status); BasicResponseHandler responseHandler = new BasicResponseHandler(); String responseBody = responseHandler.handleResponse(response).trim(); final int xmlstart = responseBody.indexOf("<?xml"); if (xmlstart > 0) { responseBody = responseBody.substring(xmlstart); } logger.debug("responseBody*>>"); logger.debug(responseBody); logger.debug("responseBody*<<"); Pattern titlePattern = Pattern.compile("(<title>)([^<]+)(</title>)"); Matcher matcher = titlePattern.matcher(responseBody); Assert.assertTrue("title element found", matcher.find()); String title = matcher.group(2); Assert.assertEquals("title", expectedTitle, title); }
From source file:org.cvasilak.jboss.mobile.admin.net.UploadToJBossServerTask.java
@Override protected JsonElement doInBackground(File... objects) { if (client == null) { return null; }//from ww w .j a va 2s . c o m final File file = objects[0]; final long length = file.length(); try { CustomMultiPartEntity multipart = new CustomMultiPartEntity( new CustomMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { //Log.d(TAG, "length=" + length + " num=" + num); publishProgress((int) ((num * 100) / length)); } }); multipart.addPart(file.getName(), new FileBody(file)); HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content"); httpRequest.setEntity(multipart); HttpResponse serverResponse = client.execute(httpRequest); BasicResponseHandler handler = new BasicResponseHandler(); String response = handler.handleResponse(serverResponse); Log.d(TAG, "<-------- " + response); return parser.parse(response).getAsJsonObject(); } catch (Exception e) { this.exception = e; cancel(true); } return null; }
From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG Date,Open,High,Low,Close,Volume,Adj Close 2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30 2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00 */// w w w .ja v a 2s .co m int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January int fromDD = Integer.valueOf(request.getParameter("b")); int fromYYYY = Integer.valueOf(request.getParameter("c")); int toMM = Integer.valueOf(request.getParameter("d")); int toDD = Integer.valueOf(request.getParameter("e")); int toYYYY = Integer.valueOf(request.getParameter("f")); String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear ValidationUtils.validateResolution(resolution); String symbol = request.getParameter("s"); ValidationUtils.validateSymbol(symbol); String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING)); String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache FileCache fileCache = JsquantContextListener.getFileCache(request); String responseBody = fileCache.get(cacheKey); if (responseBody == null) { HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString); ResponseHandler<String> responseHandler = new BasicResponseHandler(); log.debug("requesting uri=" + httpget.getURI()); responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler); //httpget.setReleaseTrigger(releaseTrigger); // no need to close? fileCache.put(cacheKey, responseBody); } String[] lines = responseBody.split("\n"); List<Stock> dayPrices = new ArrayList<Stock>(); int index = 0; for (String line : lines) if (index++ > 0 && line.length() > 0) dayPrices.add(new Stock(line)); Collections.reverse(dayPrices); index = 0; BigDecimal allTimeHighClose = new BigDecimal(0); BigDecimal stopAt = null; BigDecimal boughtPrice = null; Stock sPrev = null; for (Stock s : dayPrices) { allTimeHighClose = allTimeHighClose.max(s.adjClose); s.allTimeHighClose = allTimeHighClose; if (index > 0) { sPrev = dayPrices.get(index - 1); //true range = max(high,closeprev) - min(low,closeprev) s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose)); } int rng = 10; if (index > rng) { BigDecimal sum = new BigDecimal(0); for (Stock s2 : dayPrices.subList(index - rng, index)) sum = sum.add(s2.trueRange); s.ATR10 = sum.divide(new BigDecimal(rng)); if (allTimeHighClose.equals(s.adjClose)) { stopAt = s.adjClose.subtract(s.ATR10); } } s.stopAt = stopAt; if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) { s.order = OrderAction.SELL; s.soldPrice = s.adjClose; s.soldDifference = s.soldPrice.subtract(boughtPrice); } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null && sPrev.order == OrderAction.IGNORE) { s.order = OrderAction.BUY; boughtPrice = s.adjClose; s.boughtPrice = boughtPrice; } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) { s.order = OrderAction.HOLD; } else { s.order = OrderAction.IGNORE; } index++; } ServletOutputStream out = response.getOutputStream(); out.println(lines[0] + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference"); for (Stock s : dayPrices) out.println(s.getCSV()); }