List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str) throws UnsupportedEncodingException
From source file:sadl.run.moe.MoeTest2.java
public static void main(String[] args) throws ClientProtocolException, IOException { final String postUrl = "http://pc-kbpool-8.cs.upb.de:6543/gp/next_points/epi";// put in your url try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // Use this instead final HistoryData h = new HistoryData(); final Configuration c = new Configuration(); final PdttaParameters parameters = new PdttaParameters(); for (final Parameter p : parameters.parameters) { c.config.put(p, p.getDefault()); }//from ww w .j a v a 2 s . c om h.history.put(c, 0.5); final HttpPost post = new HttpPost(postUrl); final String s = parameters.toJsonString(20, h); // final String s = Files.readAllLines(Paths.get("testfile")).get(0); // final StringEntity postingString = new StringEntity(gson.toJson(p));// convert your pojo to json final StringEntity postingString = new StringEntity(s);// convert your pojo to json post.setEntity(postingString); System.out.println(EntityUtils.toString(post.getEntity(), "UTF-8")); post.setHeader("Content-type", "application/json"); try (CloseableHttpResponse response = httpClient.execute(post)) { final String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(responseString); } } // This is the right query // {"domain_info": {"dim": 2, "domain_bounds": [{"max": 1.0, "min": 0.0},{"max": 0.0, "min": -1.0}]}, "gp_historical_info": {"points_sampled": // [{"value_var": 0.01, "value": 0.1, "point": [0.0,0.0]}, {"value_var": 0.01, "value": 0.2, "point": [1.0,-1.0]}]}, "num_to_sample": 1} }
From source file:org.wso2.carbon.sample.http.Http.java
public static void main(String args[]) { log.info("Starting WSO2 Http Client"); HttpUtil.setTrustStoreParams();//from www . j a v a2 s.co m String url = args[0]; String username = args[1]; String password = args[2]; String sampleNumber = args[3]; String filePath = args[4]; HttpClient httpClient = new SystemDefaultHttpClient(); try { HttpPost method = new HttpPost(url); filePath = HttpUtil.getMessageFilePath(sampleNumber, filePath, url); readMsg(filePath); for (String message : messagesList) { StringEntity entity = new StringEntity(message); log.info("Sending message:"); log.info(message + "\n"); method.setEntity(entity); if (url.startsWith("https")) { processAuthentication(method, username, password); } httpClient.execute(method).getEntity().getContent().close(); } Thread.sleep(500); // Waiting time for the message to be sent } catch (Throwable t) { log.error("Error when sending the messages", t); } }
From source file:se.vgregion.pubsub.inttest.SubscriberRunner.java
public static void main(String[] args) throws Exception { LocalTestServer server = new LocalTestServer(null, null); server.register("/*", new HttpRequestHandler() { @Override//from w w w.ja v a2 s . c o m public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { String challenge = getQueryParamValue(request.getRequestLine().getUri(), "hub.challenge"); if (challenge != null) { // subscription verification, confirm System.out.println("Respond to challenge"); response.setEntity(new StringEntity(challenge)); } else if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); // System.out.println(HttpUtil.readContent(entity)); } else { System.err.println("Unknown request"); } } }); server.start(); HttpPost post = new HttpPost("http://localhost:8080/"); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("hub.callback", buildTestUrl(server, "/").toString())); parameters.add(new BasicNameValuePair("hub.mode", "subscribe")); parameters.add(new BasicNameValuePair("hub.topic", "http://feeds.feedburner.com/protocol7/main")); parameters.add(new BasicNameValuePair("hub.verify", "sync")); post.setEntity(new UrlEncodedFormEntity(parameters)); DefaultHttpClient client = new DefaultHttpClient(); client.execute(post); }
From source file:com.javaquery.aws.elasticsearch.BulkAddUpdateExample.java
public static void main(String[] args) throws UnsupportedEncodingException { /**/* ww w . ja v a 2s .com*/ * Amazon ElasticSearch Service URL: * endpoint + / + {index_name} + / + _bulk */ String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/_bulk"; /** * Records to add in elastic search * Important Note: For elastic search bulk add and update, it should be in following format. * * {header} + {new_line} // Header for next line json document * {jsonDocument} + {new_line} * {header} + {new_line} * {jsonDocument} + {new_line} * * New line at the end of String is compulsory. */ String header_one = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"123\"}}\n"; String jsonDocument_one = "{\"id\": \"123\", \"name\": \"Apple iPhone 6s\", \"stock\" : 10}\n"; String header_two = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"456\"}}\n"; String jsonDocument_two = "{\"id\": \"456\", \"name\": \"Apple iPhone 5s\", \"stock\" : 15}\n"; String jsonDocumentBulk = header_one + jsonDocument_one + header_two + jsonDocument_two; /* Convert jsonDocument to apache StringEntity */ StringEntity payload = new StringEntity(jsonDocumentBulk); /* Prepare post request to add record */ HttpPost httpPost = new HttpPost(elastic_search_url); /* Attach payload */ httpPost.setEntity(payload); /* Execute post request */ httpPostRequest(httpPost); }
From source file:org.corfudb.sharedlog.examples.ConfigClnt.java
public static void main(String[] args) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); final BufferedReader prompt = new BufferedReader(new InputStreamReader(System.in)); CorfuConfiguration C = null;/* www. j a v a 2 s .c om*/ while (true) { System.out.print("> "); String line = prompt.readLine(); if (line.startsWith("get")) { HttpGet httpget = new HttpGet("http://localhost:8000/corfu"); System.out.println("Executing request: " + httpget.getRequestLine()); HttpResponse response = (HttpResponse) httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // response.getEntity().writeTo(System.out); // System.out.println(); // System.out.println("----------------------------------------"); C = new CorfuConfiguration(response.getEntity().getContent()); } else { if (C == null) { System.out.println("configuration not set yet!"); continue; } HttpPost httppost = new HttpPost("http://localhost:8000/corfu"); httppost.setEntity(new StringEntity(C.ConfToXMLString())); System.out.println("Executing request: " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); response.getEntity().writeTo(System.out); } } // httpclient.close(); }
From source file:com.mycompany.mavenpost.HttpTest.java
public static void main(String args[]) throws UnsupportedEncodingException, IOException { System.out.println("this is a test program"); HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php"); // Request parameters and other properties. String auth = DEFAULT_USER + ":" + DEFAULT_PASS; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes()); String authHeader = "Basic " + new String(encodedAuth); //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh"; httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader); httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json"); Map<String, Object> params = new LinkedHashMap<>(); params.put("SERVICE", "customer.get"); JSONObject json = new JSONObject(); json.put("SERVICE", "customer.get"); //Map<String, Object> params2 = new LinkedHashMap<>(); //params2.put("CUSTOMER_NUMBER","5"); JSONObject array = new JSONObject(); array.put("CUSTOMER_NUMBER", "2"); json.put("FILTER", array); StringEntity param = new StringEntity(json.toString()); httppost.setEntity(param);//from w w w . j a va 2 s . c o m HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("The status code is " + statusCode); //Execute and get the response. HttpEntity entity = response.getEntity(); Header[] headers = response.getAllHeaders(); for (Header header : headers) { System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue()); } if (entity != null) { String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual // parsing JSON //JSONObject result = new JSONObject(retSrc); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(retSrc); String prettyJsonString = gson.toJson(je); System.out.println(prettyJsonString); } //if (entity != null) { // InputStream instream = entity.getContent(); // try { // final BufferedReader reader = new BufferedReader( // new InputStreamReader(instream)); // String line = null; // while ((line = reader.readLine()) != null) { // System.out.println(line); // } // reader.close(); // } finally { // instream.close(); // } //} }
From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java
public static void main(String[] args) throws Exception { if (args.length != 4 && args.length != 5) { System.err.println(// w w w . j a v a 2s. co m "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; int warmUpRounds = Integer.parseInt(args[2]); int testRounds = Integer.parseInt(args[3]); File resultDir; if (args.length == 4) { resultDir = null; } else { resultDir = new File(args[4]); if (!resultDir.exists()) { if (!resultDir.mkdirs()) { throw new RuntimeException("Failed to create result directory: " + resultDir); } } } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(resourceUrl); for (File queryFile : queryFiles) { String query = new BufferedReader(new FileReader(queryFile)).readLine(); httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}")); System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Running query: " + query); System.out.println( "--------------------------------------------------------------------------------"); // Warm-up Rounds System.out.println("Run " + warmUpRounds + " times to warm up..."); for (int i = 0; i < warmUpRounds; i++) { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); System.out.print('*'); } System.out.println(); // Test Rounds System.out.println("Run " + testRounds + " times to get response time statistics..."); long[] responseTimes = new long[testRounds]; long totalResponseTime = 0L; for (int i = 0; i < testRounds; i++) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; responseTimes[i] = responseTime; totalResponseTime += responseTime; System.out.print(responseTime + "ms "); } System.out.println(); // Store result. if (resultDir != null) { File resultFile = new File(resultDir, queryFile.getName() + ".result"); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try (BufferedInputStream bufferedInputStream = new BufferedInputStream( httpResponse.getEntity().getContent()); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) { int length; while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) { bufferedWriter.write(new String(BYTE_BUFFER, 0, length)); } } httpResponse.close(); } // Process response times. double averageResponseTime = (double) totalResponseTime / testRounds; double temp = 0; for (long responseTime : responseTimes) { temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime); } double standardDeviation = Math.sqrt(temp / testRounds); System.out.println("Average response time: " + averageResponseTime + "ms"); System.out.println("Standard deviation: " + standardDeviation); } } }
From source file:com.linkedin.pinotdruidbenchmark.PinotThroughput.java
@SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { if (args.length != 3 && args.length != 4) { System.err.println(//from ww w . ja v a 2 s. co m "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; final int numClients = Integer.parseInt(args[2]); final long endTime; if (args.length == 3) { endTime = Long.MAX_VALUE; } else { endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND; } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); final int numQueries = queryFiles.length; final HttpPost[] httpPosts = new HttpPost[numQueries]; for (int i = 0; i < numQueries; i++) { HttpPost httpPost = new HttpPost(resourceUrl); String query = new BufferedReader(new FileReader(queryFiles[i])).readLine(); httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}")); httpPosts[i] = httpPost; } final AtomicInteger counter = new AtomicInteger(0); final AtomicLong totalResponseTime = new AtomicLong(0L); final ExecutorService executorService = Executors.newFixedThreadPool(numClients); for (int i = 0; i < numClients; i++) { executorService.submit(new Runnable() { @Override public void run() { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { while (System.currentTimeMillis() < endTime) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient .execute(httpPosts[RANDOM.nextInt(numQueries)]); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; counter.getAndIncrement(); totalResponseTime.getAndAdd(responseTime); } } catch (IOException e) { e.printStackTrace(); } } }); } executorService.shutdown(); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < endTime) { Thread.sleep(REPORT_INTERVAL_MILLIS); double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND; int count = counter.get(); double avgResponseTime = ((double) totalResponseTime.get()) / count; System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms"); } }
From source file:PinotResponseTime.java
public static void main(String[] args) throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost("http://localhost:8099/query"); CloseableHttpResponse res;//from w w w . j av a 2s .co m if (STORE_RESULT) { File dir = new File(RESULT_DIR); if (!dir.exists()) { dir.mkdirs(); } } int length; // Make sure all segments online System.out.println("Test if number of records is " + RECORD_NUMBER); post.setEntity(new StringEntity("{\"pql\":\"select count(*) from tpch_lineitem\"}")); while (true) { System.out.print('*'); res = client.execute(post); boolean valid; try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) { length = in.read(BUFFER); valid = new String(BUFFER, 0, length, "UTF-8").contains("\"value\":\"" + RECORD_NUMBER + "\""); } res.close(); if (valid) { break; } else { Thread.sleep(5000); } } System.out.println("Number of Records Test Passed"); // Start Benchmark for (int i = 0; i < QUERIES.length; i++) { System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Start running query: " + QUERIES[i]); post.setEntity(new StringEntity("{\"pql\":\"" + QUERIES[i] + "\"}")); // Warm-up Rounds System.out.println("Run " + WARMUP_ROUND + " times to warm up cache..."); for (int j = 0; j < WARMUP_ROUND; j++) { res = client.execute(post); if (!isValid(res, null)) { System.out.println("\nInvalid Response, Sleep 20 Seconds..."); Thread.sleep(20000); } res.close(); System.out.print('*'); } System.out.println(); // Test Rounds int[] time = new int[TEST_ROUND]; int totalTime = 0; int validIdx = 0; System.out.println("Run " + TEST_ROUND + " times to get average time..."); while (validIdx < TEST_ROUND) { long startTime = System.currentTimeMillis(); res = client.execute(post); long endTime = System.currentTimeMillis(); boolean valid; if (STORE_RESULT && validIdx == 0) { valid = isValid(res, RESULT_DIR + File.separator + i + ".json"); } else { valid = isValid(res, null); } if (!valid) { System.out.println("\nInvalid Response, Sleep 20 Seconds..."); Thread.sleep(20000); res.close(); continue; } res.close(); time[validIdx] = (int) (endTime - startTime); totalTime += time[validIdx]; System.out.print(time[validIdx] + "ms "); validIdx++; } System.out.println(); // Process Results double avgTime = (double) totalTime / TEST_ROUND; double stdDev = 0; for (int temp : time) { stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND; } stdDev = Math.sqrt(stdDev); System.out.println("The average response time for the query is: " + avgTime + "ms"); System.out.println("The standard deviation is: " + stdDev); } } }
From source file:com.cloudhopper.sxmp.SubmitMain.java
static public void main(String[] args) throws Exception { String url = "http://localhost:9080/api/sxmp/1.0"; // create a submit request SubmitRequest submit = new SubmitRequest(); submit.setAccount(new Account("customer1", "password1")); submit.setDeliveryReport(Boolean.TRUE); MobileAddress sourceAddr = new MobileAddress(); sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404"); submit.setSourceAddress(sourceAddr); submit.setOperatorId(24);//from ww w . java2s. co m MobileAddress destAddr = new MobileAddress(); destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+14155551212"); submit.setDestinationAddress(destAddr); submit.setText( "Test abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijbcdefghij", TextEncoding.UTF_8); //submit.setText("Hello World"); // Get file to be posted HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); long totalStart = System.currentTimeMillis(); int count = 1; for (int i = 0; i < count; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(url); //ByteArrayEntity entity = new ByteArrayEntity(data); StringEntity entity = new StringEntity(SxmpWriter.createString(submit)); entity.setContentType("text/xml; charset=\"iso-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests"); double seconds = ((double) (totalEnd - totalStart)) / 1000; double smspersec = ((double) count) / seconds; logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2)); }