List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
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 w w w . j ava 2 s . c o 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:siddur.solidtrust.azure.AzureCarConstants.java
public static void main(String[] args) throws Exception { String url = OPENDATA_RWD_CSV_POST_URL; HttpPost request = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("view", VIEW)); nvps.add(new BasicNameValuePair("method", METHOD)); request.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpClient httpClient = HttpClients.custom().build(); CloseableHttpResponse response = httpClient.execute(request); InputStream is = response.getEntity().getContent(); IOUtils.copy(is, System.out); }
From source file:com.cloudhopper.sxmp.PostMO.java
static public void main(String[] args) throws Exception { String URL = "https://sms.twitter.com/receive/cloudhopper"; String text = "HELP"; String srcAddr = "+16504304922"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "20"; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(text.getBytes()) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try {//from www .j a va2 s.c om HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:postenergy.PostHttpClient.java
public static void main(String[] args) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://iplant.dk/addData.php?n=mindass"); try {//w w w .j a v a2 s .c o m List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("?n", "=mindass")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); if (line.startsWith("Input:")) { String key = line.substring(6); // do something with the key System.out.println("key:" + key); } } } catch (IOException e) { System.out.println("There was an error: " + e); } }
From source file:TTrestclient.TeachTimeRESTclient.java
/** * @param args the command line arguments *//*from www . j a va 2s. co m*/ public static void main(String[] args) { TeachTimeRESTclient instance = new TeachTimeRESTclient(); //1 -- Lista entries (JSON) /*System.out.println("1 -- Utente (JSON)"); //creiamo la richiesta (GET) HttpGet get_request = new HttpGet(baseURI + "/users/1"); get_request.setHeader("Accept", "application/json"); instance.execute_and_dump(get_request); System.out.println(); //6 -- Creazione System.out.println("6 -- Creazione entry utente"); HttpPost post_request = new HttpPost(baseURI + "/users"); //per una richiesta POST, prepariamo anche il payload specificandone il tipo HttpEntity payload = new StringEntity(dummy_json_entry, ContentType.APPLICATION_JSON); //e lo inseriamo nella richiesta post_request.setEntity(payload); instance.execute_and_dump(post_request); System.out.println();*/ HttpPost post = new HttpPost(baseURI + "/subjects/3"); HttpEntity payload = new StringEntity("{\"nome\":\"diocane\",\"materia_key\":3}", ContentType.APPLICATION_JSON); post.setEntity(payload); instance.execute_and_dump(post); }
From source file:com.cloudhopper.sxmp.PostUTF8MO.java
static public void main(String[] args) throws Exception { String URL = "https://sms-staging.twitter.com/receive/cloudhopper"; // this is a Euro currency symbol //String text = "\u20AC"; // shorter arabic //String text = "\u0623\u0647\u0644\u0627"; // even longer arabic //String text = "\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649"; String text = ""; for (int i = 0; i < 140; i++) { text += "\u0623"; }//from w ww .j a v a2 s. c o m String srcAddr = "+14159129228"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "23"; //text += " " + ticketId; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <ticketId>" + ticketId + "</ticketId>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"UTF-8\">" + HexUtil.toHexString(text.getBytes("UTF-8")) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:org.eclipse.lyo.adapter.tdb.clients.OSLCTriplestoreAdapterResourceCreationClient.java
public static void main(String[] args) { String baseHTTPURI = "http://localhost:" + OSLC4JTDBApplication.portNumber + "/oslc4jtdb"; String projectId = "default"; // URI of the HTTP request String tdbResourceCreationFactoryURI = baseHTTPURI + "/services/" + projectId + "/resources"; // create RDF to add to the triplestore Model resourceRDFModel = ModelFactory.createDefaultModel(); Resource resource = ResourceFactory .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newBlock4"); Property property = ResourceFactory/*from w ww . j a va2 s .c om*/ .createProperty("http://localhost:8585/oslc4jtdb/services/default/resources/newProperty4"); RDFNode object = ResourceFactory .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newObject4"); resourceRDFModel.add(resource, property, object); StringWriter out = new StringWriter(); resourceRDFModel.write(out, "RDF/XML"); resourceRDFModel.write(System.out); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(tdbResourceCreationFactoryURI); String xml = out.toString(); HttpEntity entity; try { entity = new ByteArrayEntity(xml.getBytes("UTF-8")); post.setEntity(entity); post.setHeader("Accept", "application/rdf+xml"); HttpResponse response = client.execute(post); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.dlmu.heipacker.crawler.client.QuickStart.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://targethost/homepage"); HttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST either fully consume the response content or abort request // execution by calling HttpGet#releaseConnection(). try {/*from w w w . j a v a2 s. c om*/ System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { httpGet.releaseConnection(); } HttpPost httpPost = new HttpPost("http://targethost/login"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { httpPost.releaseConnection(); } }
From source file:PinotThroughput.java
@SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { final int numQueries = QUERIES.length; final Random random = new Random(RANDOM_SEED); final AtomicInteger counter = new AtomicInteger(0); final AtomicLong totalResponseTime = new AtomicLong(0L); final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS); for (int i = 0; i < NUM_CLIENTS; i++) { executorService.submit(new Runnable() { @Override/*w w w. j a v a 2 s.c o m*/ public void run() { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost("http://localhost:8099/query"); CloseableHttpResponse res; while (true) { String query = QUERIES[random.nextInt(numQueries)]; post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}")); long start = System.currentTimeMillis(); res = client.execute(post); res.close(); counter.getAndIncrement(); totalResponseTime.getAndAdd(System.currentTimeMillis() - start); } } catch (IOException e) { e.printStackTrace(); } } }); } long startTime = System.currentTimeMillis(); while (true) { 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:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception// w w w . ja va 2 s.c o m */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }