List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:com.tianya.ClientMultipartFormPost.java
public static void main(String[] args) throws Exception { /*/*from w ww .j av a 2 s .c om*/ if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } */ HttpClient httpclient = new DefaultHttpClient(); String posturl = "http://letushow.com/submit"; preGet(httpclient); try { HttpPost httppost = new HttpPost(posturl); FileBody bin = new FileBody(new File("/Users/gypsai/Desktop/letushow/let.gif")); StringBody title = new StringBody("let"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("imgfile", bin); reqEntity.addPart("csrf_token", new StringBody(csrf_token)); reqEntity.addPart("title", title); reqEntity.addPart("type", new StringBody("local")); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { // System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println(iotostring(response.getEntity().getContent())); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
From source file:com.dlmu.heipacker.crawler.client.ClientChunkEncodedPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1);/*from www . j a v a2s. co m*/ } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost( "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); File file = new File(args[0]); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // It may be more appropriate to use FileEntity class in this particular // instance but we are using a more generic InputStreamEntity to demonstrate // the capability to stream out data from any arbitrary source // // FileEntity entity = new FileEntity(file, "binary/octet-stream"); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } EntityUtils.consume(resEntity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:net.modelbased.proasense.storage.registry.StorageRegistryScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistryScrapRateTestClient client = new StorageRegistryScrapRateTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;//from w w w. ja va 2 s. com // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for machine list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MACHINE LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for machine properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("machineId", "IMM1")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MACHINE PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/list"); try { HttpGet query21 = new HttpGet(requestUrl.toString()); query21.setHeader("Content-type", "application/json"); response = client.execute(query21); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", "dustParticleSensor")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/list"); try { HttpGet query31 = new HttpGet(requestUrl.toString()); query31.setHeader("Content-type", "application/json"); response = client.execute(query31); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("PRODUCT LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("PRODUCT PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/mould/list"); try { HttpGet query41 = new HttpGet(requestUrl.toString()); query41.setHeader("Content-type", "application/json"); response = client.execute(query41); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MOULD LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query42 = new HttpGet(requestUrl.toString()); query42.setHeader("Content-type", "application/json"); response = client.execute(query42); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MOULD PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:ebay.Ebay.java
/** * @param args the command line arguments *//*from ww w . j a va2 s . c o m*/ public static void main(String[] args) { HttpClient client = null; HttpResponse response = null; BufferedReader rd = null; Document doc = null; String xml = ""; EbayDAO<Producto> db = new EbayDAO<>(Producto.class); String busqueda; while (true) { busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda"); if (busqueda != null) { busqueda = busqueda.replaceAll(" ", "%20"); try { client = new DefaultHttpClient(); /* peticion GET */ HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems" + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords=" + busqueda + "&siteid=0" + "&responseencoding=XML"); /* se ejecuta la peticion GET */ response = client.execute(request); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); /* comienza la lectura de la respuesta a la peticion GET */ String line; while ((line = rd.readLine()) != null) { xml += line + "\n"; } } catch (IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } /* creamos nuestro documentBulder(documento constructor) y obtenemos nuestro objeto documento apartir de documentBuilder */ try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } Element raiz = doc.getDocumentElement(); if (raiz == null) { System.exit(0); } if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) { NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes(); for (int i = 0; i < array.getLength(); ++i) { Node n = array.item(i); if (n.getNodeType() != Node.TEXT_NODE) { Producto p = new Producto(); if (((Element) n).getElementsByTagName("ItemID").item(0) != null) p.setId(new Long( ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("EndTime").item(0) != null) p.setEndtime( ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null) p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("ListingType").item(0) != null) p.setListingtype( ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent()); if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null) p.setGalleryurl( ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent()); if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null) p.setPrimarycategoryid(new Integer(((Element) n) .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null) p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("BidCount").item(0) != null) p.setBidcount(new Integer( ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null) p.setConvertedcurrentprice(new Double(((Element) n) .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null) p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null) p.setTimeleft( ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent()); if (((Element) n).getElementsByTagName("Title").item(0) != null) p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null) p.setShippingservicecost(new Double(((Element) n) .getElementsByTagName("ShippingServiceCost").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ShippingType").item(0) != null) p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("WatchCount").item(0) != null) p.setWatchcount(new Integer( ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null) p.setListedshippingservicecost( new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost") .item(0).getTextContent())); try { db.insert(p); } catch (Exception e) { db.update(p); } } } } Ventana.crear(xml); } else System.exit(0); } }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);/*from w w w. java2s . c om*/ return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageReaderMongoServiceTestClient client = new StorageReaderMongoServiceTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_READER_SERVICE_URL = "http://192.168.84.34:8080/storage-reader"; String QUERY_SIMPLE_SENSORID = "1000692"; String QUERY_SIMPLE_STARTTIME = "1387565891068"; String QUERY_SIMPLE_ENDTIME = "1387565996633"; String QUERY_SIMPLE_PROPERTYKEY = "value"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;/*from w w w.j a v a2 s . co m*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.DEFAULT: " + body); // The result is an array of simple events serialized as JSON using Apache Thrift. // The simple events can be deserialized into Java objects using Apache Thrift. ObjectMapper mapper = new ObjectMapper(); JsonNode nodeArray = mapper.readTree(body); for (JsonNode node : nodeArray) { byte[] bytes = node.toString().getBytes(); TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); SimpleEvent event = new SimpleEvent(); deserializer.deserialize(event, bytes); System.out.println(event.toString()); } } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/average"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Get status code status = response.getStatusLine().getStatusCode(); if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.AVERAGE: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/maximum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query13 = new HttpGet(requestUrl.toString()); query13.setHeader("Content-type", "application/json"); response = client.execute(query13); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MAXIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/minimum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query14 = new HttpGet(requestUrl.toString()); query14.setHeader("Content-type", "application/json"); response = client.execute(query14); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MINIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:httpclient.UploadAction.java
public static void main(String[] args) throws FileNotFoundException { File targetFile1 = new File("F:\\2.jpg"); // File targetFile2 = new File("F:\\1.jpg"); FileInputStream fis1 = new FileInputStream(targetFile1); // FileInputStream fis2 = new FileInputStream(targetFile2); // String targetURL = // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do"; String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do"; HttpPost filePost = new HttpPost(targetURL); try {//w w w .j a va 2 s. com // ????? HttpClient client = new DefaultHttpClient(); // FormBodyPart fbp1 = new FormBodyPart("file1", new // FileBody(targetFile1)); // FormBodyPart fbp2 = new FormBodyPart("file2", new // FileBody(targetFile2)); // FormBodyPart fbp3 = new FormBodyPart("file3", new // FileBody(targetFile3)); // List<FormBodyPart> picList = new ArrayList<FormBodyPart>(); // picList.add(fbp1); // picList.add(fbp2); // picList.add(fbp3); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17"); Map<String, Object> map = new HashMap<String, Object>(); String jsonStr = JSON.toJSONString(paramMap); map.put("cid", 321); map.put("request", jsonStr); String jsonString = JSON.toJSONString(map); MultipartEntity multiEntity = new MultipartEntity(); Charset charset = Charset.forName("UTF-8"); multiEntity.addPart("request", new StringBody(jsonString, charset)); multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg")); // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2, // "1.jpg")); filePost.setEntity(multiEntity); HttpResponse response = client.execute(filePost); int code = response.getStatusLine().getStatusCode(); System.out.println(code); if (HttpStatus.SC_OK == code) { System.out.println("?"); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } } finally { instream.close(); } } } else { System.out.println(""); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java
public static void main(String[] args) { // Get benchmark properties StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark(); benchmark.loadClientProperties();/* w ww . jav a 2 s . co m*/ // ProaSense Storage Reader Service configuration properties String STORAGE_READER_SERVICE_URL = benchmark.clientProperties .getProperty("proasense.storage.reader.service.url"); String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.collectionid"); String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.starttime"); String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.endtime"); String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.collectionid"); String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.starttime"); String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.endtime"); String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.collectionid"); String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.starttime"); String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.endtime"); String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.collectionid"); String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.starttime"); String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.endtime"); String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.collectionid"); String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.starttime"); String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.endtime"); String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.collectionid"); String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.starttime"); String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.endtime"); String propertyKey = "value"; // Default HTTP client and common property variables for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null; StatusLine status = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); try { status = client.execute(query11).getStatusLine(); System.out.println("SIMPLE.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/value"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", "value")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL); query12.setHeader("Content-type", "application/json"); try { status = client.execute(query12).getStatusLine(); System.out.println("SIMPLE.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL); query13.setHeader("Content-type", "application/json"); try { status = client.execute(query13).getStatusLine(); System.out.println("SIMPLE.MAXIMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL); query14.setHeader("Content-type", "application/json"); try { status = client.execute(query14).getStatusLine(); System.out.println("SIMPLE.MINUMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for derived events HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL); query21.setHeader("Content-type", "application/json"); try { status = client.execute(query21).getStatusLine(); System.out.println("DERIVED.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for derived events HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL); query22.setHeader("Content-type", "application/json"); try { status = client.execute(query22).getStatusLine(); System.out.println("DERIVED.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL); query23.setHeader("Content-type", "application/json"); try { status = client.execute(query23).getStatusLine(); System.out.println("DERIVED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL); query24.setHeader("Content-type", "application/json"); try { status = client.execute(query24).getStatusLine(); System.out.println("DERIVED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for predicted events HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL); query31.setHeader("Content-type", "application/json"); try { status = client.execute(query31).getStatusLine(); System.out.println("PREDICTED.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for predicted events HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL); query32.setHeader("Content-type", "application/json"); try { status = client.execute(query32).getStatusLine(); System.out.println("PREDICTED.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for predicted events HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL); query33.setHeader("Content-type", "application/json"); try { status = client.execute(query33).getStatusLine(); System.out.println("PREDICTED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL); query34.setHeader("Content-type", "application/json"); try { status = client.execute(query34).getStatusLine(); System.out.println("PREDICTED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for anomaly events HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL); query41.setHeader("Content-type", "application/json"); try { status = client.execute(query41).getStatusLine(); System.out.println("ANOMALY.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for recommendation events HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL); query51.setHeader("Content-type", "application/json"); try { status = client.execute(query51).getStatusLine(); System.out.println("RECOMMENDATION.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for recommendation events HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL); query52.setHeader("Content-type", "application/json"); try { status = client.execute(query52).getStatusLine(); System.out.println("RECOMMENDATION.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL); query53.setHeader("Content-type", "application/json"); try { status = client.execute(query53).getStatusLine(); System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("RECOMMENDATION.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for feedback events HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("FEEDBACK.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:org.craftercms.social.UCGRestServicesTest.java
public static void main(String[] args) throws Exception { ProfileClient profileRestClient = new ProfileRestClientImpl(); String token = profileRestClient.getAppToken("craftersocial", "craftersocial"); Tenant tenant = profileRestClient.getTenantByName(token, "testing"); String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId()); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("ticket", ticket)); qparams.add(new BasicNameValuePair("target", "testing")); qparams.add(new BasicNameValuePair("textContent", "Content")); URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json", URLEncodedUtils.format(qparams, HTTP.UTF_8), null); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(uri); File file = new File( "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt"); MultipartEntity me = new MultipartEntity(); //The usual form parameters can be added this way //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ; //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ; /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part. This part will be considered as file part and the rest of them as usual form-data parts*/ FileBody fileBody = new FileBody(file, "application/octect-stream"); //me.addPart("ticket", new StringBody(token)) ; //me.addPart("target", new StringBody("my-test")) ; me.addPart("attachments", fileBody); httppost.setEntity(me);/*from www . jav a2s. c om*/ httpclient.execute(httppost); }
From source file:CourserankConnector.java
public static void main(String[] args) throws Exception { /////////////////////////////////////// //Tagger init //MaxentTagger tagger = new MaxentTagger("models/english-left3words-distsim.tagger"); /////from www .j av a2s .c o m //CLIENT INITIALIZATION ImportData importCourse = new ImportData(); HttpClient httpclient = new DefaultHttpClient(); httpclient = WebClientDevWrapper.wrapClient(httpclient); try { /* httpclient.getCredentialsProvider().setCredentials( new AuthScope(null, -1), new UsernamePasswordCredentials("eadrian", "eactresp1")); */ ////////////////////////////////////////////////// //Get Course Bulletin Departments page List<Course> courses = new ArrayList<Course>(); HttpGet httpget = new HttpGet("http://explorecourses.stanford.edu"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); String bulletinpage = ""; //STORE RETURNED HTML TO BULLETINPAGE if (entity != null) { //System.out.println("Response content length: " + entity.getContentLength()); InputStream i = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { bulletinpage += line; //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(entity); /////////////////////////////////////////////////////////////////////////////// //Login to Courserank httpget = new HttpGet("https://courserank.com/stanford/main"); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); String page = ""; if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); InputStream i = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { page += line; //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(entity); //////////////////////////////////////////////////// //POST REQUEST LOGIN HttpPost post = new HttpPost("https://www.courserank.com/stanford/main"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(2); pairs.add(new BasicNameValuePair("RT", "")); pairs.add(new BasicNameValuePair("action", "login")); pairs.add(new BasicNameValuePair("password", "trespass")); pairs.add(new BasicNameValuePair("username", "eaconte@stanford.edu")); post.setEntity(new UrlEncodedFormEntity(pairs)); System.out.println("executing request" + post.getRequestLine()); HttpResponse resp = httpclient.execute(post); HttpEntity ent = resp.getEntity(); System.out.println("----------------------------------------"); if (ent != null) { System.out.println("Response content length: " + ent.getContentLength()); InputStream i = ent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(ent); /////////////////////////////////////////////////// //THIS STEP MAY NOT BE NEEDED BUT GETS MAIN PROFILE PAGE HttpGet gethome = new HttpGet("https://www.courserank.com/stanford/home"); System.out.println("executing request" + gethome.getRequestLine()); HttpResponse gresp = httpclient.execute(gethome); HttpEntity gent = gresp.getEntity(); System.out.println("----------------------------------------"); if (ent != null) { System.out.println("Response content length: " + gent.getContentLength()); InputStream i = gent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { //System.out.println(line); } br.close(); i.close(); } ///////////////////////////////////////////////////////////////////////////////// //Parse Bulletin String results = getToken(bulletinpage, "RESULTS HEADER", "Additional Searches"); String[] depts = results.split("href"); //SPLIT FOR EACH DEPARTMENT LINK, ITERATE boolean ready = false; for (int i = 1; i < depts.length; i++) { //EXTRACT LINK, DEPARTMENT NAME AND ABBREVIATION String dept = new String(depts[i]); String abbr = getToken(dept, "(", ")"); String name = getToken(dept, ">", "("); name.trim(); //System.out.println(tagger.tagString(name)); String link = getToken(dept, "=\"", "\">"); System.out.println(name + " : " + abbr + " : " + link); System.out.println("======================================================================"); if (i <= 10 || i >= 127) //values to keep it to undergraduate courses. Excludes law, med, business, overseas continue; /*if (i<=46) continue; */ //Start at BIOHOP /*if (abbr.equals("INTNLREL")) ready = true; if (!ready) continue;*/ //Construct department course search URL //Then request page String URL = "http://explorecourses.stanford.edu/" + link + "&filter-term-Autumn=on&filter-term-Winter=on&filter-term-Spring=on"; httpget = new HttpGet(URL); //System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); //ystem.out.println("----------------------------------------"); //System.out.println(response.getStatusLine()); String rpage = ""; if (entity != null) { //System.out.println("Response content length: " + entity.getContentLength()); InputStream in = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { rpage += line; //System.out.println(line); } br.close(); in.close(); } EntityUtils.consume(entity); //Process results page List<Course> deptCourses = new ArrayList<Course>(); List<Course> result = processResultPage(rpage); deptCourses.addAll(result); //While there are more result pages, keep going boolean more = (!(result.size() == 0) && (result.get((result.size() - 1)).courseNumber < 299)); boolean morepages = anotherPage(rpage); while (morepages && more) { URL = nextURL(URL); httpget = new HttpGet(URL); //System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); //System.out.println("----------------------------------------"); //System.out.println(response.getStatusLine()); rpage = ""; if (entity != null) { //System.out.println("Response content length: " + entity.getContentLength()); InputStream in = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { rpage += line; //System.out.println(line); } br.close(); in.close(); } EntityUtils.consume(entity); morepages = anotherPage(rpage); result = processResultPage(rpage); deptCourses.addAll(result); more = (!(result.size() == 0) && (result.get((result.size() - 1)).courseNumber < 299)); /*String mores = more? "yes": "no"; String pagess = morepages?"yes":"no"; System.out.println("more: "+mores+" morepages: "+pagess); System.out.println("more");*/ } //Get course ratings for all department courses via courserank deptCourses = getRatings(httpclient, abbr, deptCourses); for (int j = 0; j < deptCourses.size(); j++) { Course c = deptCourses.get(j); System.out.println("" + c.title + " : " + c.rating); c.tags = name; c.code = c.code.trim(); c.department = name; c.deptAB = abbr; c.writeToDatabase(); //System.out.println(tagger.tagString(c.title)); } } if (!page.equals("")) return; /////////////////////////////////////////////////// //Get Course Bulletin Department courses /* httpget = new HttpGet("https://courserank.com/stanford/main"); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); page = ""; if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); InputStream i = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { page +=line; //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(entity); //////////////////////////////////////////////////// //POST REQUEST LOGIN HttpPost post = new HttpPost("https://www.courserank.com/stanford/main"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(2); pairs.add(new BasicNameValuePair("RT", "")); pairs.add(new BasicNameValuePair("action", "login")); pairs.add(new BasicNameValuePair("password", "trespass")); pairs.add(new BasicNameValuePair("username", "eaconte@stanford.edu")); post.setEntity(new UrlEncodedFormEntity(pairs)); System.out.println("executing request" + post.getRequestLine()); HttpResponse resp = httpclient.execute(post); HttpEntity ent = resp.getEntity(); System.out.println("----------------------------------------"); if (ent != null) { System.out.println("Response content length: " + ent.getContentLength()); InputStream i = ent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(ent); /////////////////////////////////////////////////// //THIS STEP MAY NOT BE NEEDED BUT GETS MAIN PROFILE PAGE HttpGet gethome = new HttpGet("https://www.courserank.com/stanford/home"); System.out.println("executing request" + gethome.getRequestLine()); HttpResponse gresp = httpclient.execute(gethome); HttpEntity gent = gresp.getEntity(); System.out.println("----------------------------------------"); if (ent != null) { System.out.println("Response content length: " + gent.getContentLength()); InputStream i = gent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { //System.out.println(line); } br.close(); i.close(); } //////////////////////////////////////// //GETS FIRST PAGE OF RESULTS EntityUtils.consume(gent); post = new HttpPost("https://www.courserank.com/stanford/search_results"); pairs = new ArrayList<NameValuePair>(2); pairs.add(new BasicNameValuePair("filter_term_currentYear", "on")); pairs.add(new BasicNameValuePair("query", "")); post.setEntity(new UrlEncodedFormEntity(pairs)); System.out.println("executing request" + post.getRequestLine()); resp = httpclient.execute(post); ent = resp.getEntity(); System.out.println("----------------------------------------"); String rpage = ""; if (ent != null) { System.out.println("Response content length: " + ent.getContentLength()); InputStream i = ent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { rpage += line; System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(ent); //////////////////////////////////////////////////// //PARSE FIRST PAGE OF RESULTS //int index = rpage.indexOf("div class=\"searchItem"); String []classSplit = rpage.split("div class=\"searchItem"); for (int i=1; i<classSplit.length; i++) { String str = classSplit[i]; //ID String CID = getToken(str, "course?id=","\">"); // CODE String CODE = getToken(str,"class=\"code\">" ,":</"); //TITLE String NAME = getToken(str, "class=\"title\">","</"); //DESCRIP String DES = getToken(str, "class=\"description\">","</"); //TERM String TERM = getToken(str, "Terms:", "|"); //UNITS String UNITS = getToken(str, "Units:", "<br/>"); //WORKLOAD String WLOAD = getToken(str, "Workload:", "|"); //GER String GER = getToken(str, "GERs:", "</d"); //RATING int searchIndex = 0; float rating = 0; while (true) { int ratingIndex = str.indexOf("large_Full", searchIndex); if (ratingIndex ==-1) { int halfratingIndex = str.indexOf("large_Half", searchIndex); if (halfratingIndex == -1) break; else rating += .5; break; } searchIndex = ratingIndex+1; rating++; } String RATING = ""+rating; //GRADE String GRADE = getToken(str, "div class=\"unofficialGrade\">", "</"); if (GRADE.equals("NOT FOUND")) { GRADE = getToken(str, "div class=\"officialGrade\">", "</"); } //REVIEWS String REVIEWS = getToken(str, "class=\"ratings\">", " ratings"); System.out.println(""+CODE+" : "+NAME + " : "+CID); System.out.println("----------------------------------------"); System.out.println("Term: "+TERM+" Units: "+UNITS+ " Workload: "+WLOAD + " Grade: "+ GRADE); System.out.println("Rating: "+RATING+ " Reviews: "+REVIEWS); System.out.println("=========================================="); System.out.println(DES); System.out.println("=========================================="); } /////////////////////////////////////////////////// //GETS SECOND PAGE OF RESULTS post = new HttpPost("https://www.courserank.com/stanford/search_results"); pairs = new ArrayList<NameValuePair>(2); pairs.add(new BasicNameValuePair("filter_term_currentYear", "on")); pairs.add(new BasicNameValuePair("page", "2")); pairs.add(new BasicNameValuePair("query", "")); post.setEntity(new UrlEncodedFormEntity(pairs)); System.out.println("executing request" + post.getRequestLine()); resp = httpclient.execute(post); ent = resp.getEntity(); System.out.println("----------------------------------------"); if (ent != null) { System.out.println("Response content length: " + ent.getContentLength()); InputStream i = ent.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { //System.out.println(line); } br.close(); i.close(); } EntityUtils.consume(ent); /* httpget = new HttpGet("https://github.com/"); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); page = ""; if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); InputStream i = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(i)); String line; while ((line = br.readLine()) != null) { page +=line; System.out.println(line); } br.close(); i.close(); }*/ EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }