List of usage examples for org.apache.http.client ResponseHandler handleResponse
T handleResponse(HttpResponse response) throws ClientProtocolException, IOException;
From source file:mai.cn.film.auth.ClientAuthentication.java
public static void main(String[] args) throws Exception { HttpHost targetHost = new HttpHost("www.filmaffinity.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*w ww . j av a2 s. c o m*/ httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("picarus", "8C8PPkEc")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("http://www.filmaffinity.com/en/myvotes.php"); System.out.println("executing request" + httpget.getRequestLine()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse response = httpclient.execute(httpget); String responseBody = responseHandler.handleResponse(response); int code = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); System.out.println("----------------------------------------"); System.out.println("Status:" + code + " " + response.getStatusLine().getReasonPhrase()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } 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(); } }
From source file:net.modelbased.proasense.storage.registry.StorageRegistrySensorDataTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistrySensorDataTestClient client = new StorageRegistrySensorDataTestClient(); // 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;/* ww w . j a v a 2 s.co m*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // 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", "visualInspection")); 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()); } }
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 ww w.j a v a 2s .c o m*/ // 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: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 www .j a v a 2 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:nl.coralic.beta.sms.utils.http.HttpHandler.java
private static Response doPost(String url, List<NameValuePair> postdata) { HttpClient httpclient = getHttpClient(); try {//from w w w .j av a 2 s . c om HttpPost httpost = new HttpPost(url); httpost.setEntity(new UrlEncodedFormEntity(postdata, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpost); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> responseHandler = new BasicResponseHandler(); return new Response(responseHandler.handleResponse(response)); } else { return new Response(R.string.ERR_PROV_NO_RESP); } } catch (Exception e) { return new Response(R.string.ERR_CONN_ERR); } finally { // Release the resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.hackathon.completeroute.dao.factory.JsonDAOFactory.java
/** * @param resp http response from server * @return body from response. <b>HTTP Response is passed in, and the String * from the Body is returned.</b> * @throws Exception/*from www .j a v a 2 s . c om*/ */ private static String getResponse(HttpResponse resp) throws Exception { ResponseHandler<String> handler = new BasicResponseHandler(); return handler.handleResponse(resp); }
From source file:Main.java
private static void ExecutePostRequest(HttpClient client, HttpRequestBase method, ResponseHandler<String> responseHandler) { BasicHttpResponse errorResponse = new BasicHttpResponse(new ProtocolVersion("HTTP_ERROR", 1, 1), 500, "ERROR"); try {/*from w w w . ja v a 2 s. c o m*/ client.execute(method, responseHandler); } catch (Exception e) { errorResponse.setReasonPhrase(e.getMessage()); try { responseHandler.handleResponse(errorResponse); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Upload metadata file.//ww w. j av a 2 s. c o m * * @param endPoint the end point * @param xml the xml * @param client the client (optional) * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws JSONException the JSON exception */ private static String uploadMetadataFile(String endPoint, InputStream xml, CloseableHttpClient client) throws IOException, JSONException { boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpPost request = new HttpPost(endPoint + TestObjects_URL + "?action=upload"); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("fileupload", xml, ContentType.TEXT_XML, "file.xml"); HttpEntity entity = builder.build(); request.setEntity(entity); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); return jsonRoot.getJSONObject("testObject").getString("id"); } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestObjects_URL); return null; } } catch (Exception e) { Log.error(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e); return null; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Checks if is passed./*from www .j a v a2 s. c o m*/ * * @param endPoint the end point * @param testId the test id * @param client the client (optional) * @return the string * @throws Exception */ public static String isPassed(String endPoint, String testId, CloseableHttpClient client) throws Exception { if (testId == null) { throw new Exception(""); } boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); try { return jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns") .getJSONObject("TestRun").getString("status"); } catch (JSONException e) { return null; } } else if (response.getStatusLine().getStatusCode() == 404) { throw new NotFoundException("Test not found"); } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress"); } } catch (Exception e) { Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e); throw e; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } return null; }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Checks if is ready.//from w ww . j a v a 2 s.com * * @param endPoint the end point * @param testId the test id * @param client the client (optional) * @return true, if is ready * @throws Exception */ public static boolean isReady(String endPoint, String testId, CloseableHttpClient client) throws Exception { if (testId == null) { return false; } boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + TestRuns_URL + "/" + testId + "/progress"); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); // Completed when estimated number of Test Steps is equal to completed Test Steps // Somehow this condition is necessary but not sufficient // so another check on real value of test is evaluated return jsonRoot.getInt("val") == jsonRoot.getInt("max") & InspireValidatorUtils.isPassed(endPoint, testId, client) != null; } else if (response.getStatusLine().getStatusCode() == 404) { throw new NotFoundException("Test not found"); } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL + "?view=progress"); } } catch (NotFoundException e) { throw e; } catch (Exception e) { Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e); throw e; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } return false; }