List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java
/** * This method sends HTTP request to add order. * * @param user/*from w w w. j av a 2s. co m*/ * @param handler * @param orderInfo * @return */ public static String sendAddOrderRequest(User user, Handler handler, TableReservationInfo orderInfo) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); HttpConnectionParams.setSoTimeout(httpParameters, 15000); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(ADD_ORDER_URL); Log.e(TAG, "ADD_ORDER_URL = " + ADD_ORDER_URL); MultipartEntity multipartEntity = new MultipartEntity(); // user details String userType = null; String orderUUID = null; try { if (user.getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) { userType = "facebook"; multipartEntity.addPart("order_customer_name", new StringBody( user.getUserFirstName() + " " + user.getUserLastName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.TWITTER) { userType = "twitter"; multipartEntity.addPart("order_customer_name", new StringBody(user.getUserName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.IBUILDAPP) { userType = "ibuildapp"; multipartEntity.addPart("order_customer_name", new StringBody(user.getUserName(), Charset.forName("UTF-8"))); } else if (user.getAccountType() == User.ACCOUNT_TYPES.GUEST) { userType = "guest"; multipartEntity.addPart("order_customer_name", new StringBody("Guest", Charset.forName("UTF-8"))); } multipartEntity.addPart("user_type", new StringBody(userType, Charset.forName("UTF-8"))); multipartEntity.addPart("user_id", new StringBody(user.getAccountId(), Charset.forName("UTF-8"))); multipartEntity.addPart("app_id", new StringBody(orderInfo.getAppid(), Charset.forName("UTF-8"))); multipartEntity.addPart("module_id", new StringBody(orderInfo.getModuleid(), Charset.forName("UTF-8"))); // order UUID orderUUID = UUID.randomUUID().toString(); multipartEntity.addPart("order_uid", new StringBody(orderUUID, Charset.forName("UTF-8"))); // order details Date tempDate = orderInfo.getOrderDate(); tempDate.setHours(orderInfo.getOrderTime().houres); tempDate.setMinutes(orderInfo.getOrderTime().minutes); tempDate.getTimezoneOffset(); String timeZone = timeZoneToString(); multipartEntity.addPart("time_zone", new StringBody(timeZone, Charset.forName("UTF-8"))); multipartEntity.addPart("order_date_time", new StringBody(Long.toString(tempDate.getTime() / 1000), Charset.forName("UTF-8"))); multipartEntity.addPart("order_persons", new StringBody(Integer.toString(orderInfo.getPersonsAmount()), Charset.forName("UTF-8"))); multipartEntity.addPart("order_spec_request", new StringBody(orderInfo.getSpecialRequest(), Charset.forName("UTF-8"))); multipartEntity.addPart("order_customer_phone", new StringBody(orderInfo.getPhoneNumber(), Charset.forName("UTF-8"))); multipartEntity.addPart("order_customer_email", new StringBody(orderInfo.getCustomerEmail(), Charset.forName("UTF-8"))); // add security part multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8"))); } catch (Exception e) { Log.d("", ""); } httppost.setEntity(multipartEntity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { String strResponseSaveGoal = httpclient.execute(httppost, responseHandler); Log.d("sendAddOrderRequest", ""); String res = JSONParser.parseQueryError(strResponseSaveGoal); if (res == null || res.length() == 0) { return orderUUID; } else { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } } catch (ConnectTimeoutException conEx) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } catch (ClientProtocolException ex) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } catch (IOException ex) { handler.sendEmptyMessage(ADD_REQUEST_ERROR); return null; } }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Gets the tests./* w w w . ja v a2 s . c o m*/ * * @param endPoint the end point * @param client the client (optional) * @return the tests */ private static List<String> getTests(String endPoint, CloseableHttpClient client) { boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpGet request = new HttpGet(endPoint + ExecutableTestSuites_URL); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { List<String> testList = new ArrayList<>(); ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); JSONObject etfItemCollection = jsonRoot.getJSONObject("EtfItemCollection"); JSONObject executableTestSuites = etfItemCollection.getJSONObject("executableTestSuites"); JSONArray executableTestSuiteArray = executableTestSuites.getJSONArray("ExecutableTestSuite"); for (int i = 0; i < executableTestSuiteArray.length(); i++) { JSONObject test = executableTestSuiteArray.getJSONObject(i); boolean ok = false; for (String testToRun : TESTS_TO_RUN) { ok = ok || testToRun.equals(test.getString("label")); } if (ok) { testList.add(test.getString("id")); } } return testList; } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + ExecutableTestSuites_URL); return null; } } catch (Exception e) { Log.error(Log.SERVICE, "Exception in 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:com.google.appinventor.components.runtime.util.WebServiceUtil.java
/** * Make a post command to serviceURL with params and return the * response String.// w w w .j a va 2 s. c o m * * @param serviceURL The URL of the server to post to. * @param commandName The path to the command. * @param params A List of NameValuePairs to send as parameters * with the post. * @param callback A callback function that accepts a String on * success. */ public void postCommand(final String serviceURL, final String commandName, List<NameValuePair> params, AsyncCallbackPair<String> callback) { Log.d(LOG_TAG, "Posting " + commandName + " to " + serviceURL + " with arguments " + params); if (serviceURL == null || serviceURL.equals("")) { callback.onFailure("No service url to post command to."); } final HttpPost httpPost = new HttpPost(serviceURL + "/" + commandName); if (params == null) { params = new ArrayList<NameValuePair>(); } try { String httpResponseString; ResponseHandler<String> responseHandler = new BasicResponseHandler(); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpPost.setHeader("Accept", "application/json"); httpResponseString = httpClient.execute(httpPost, responseHandler); callback.onSuccess(httpResponseString); } catch (UnsupportedEncodingException e) { Log.w(LOG_TAG, e); callback.onFailure("Failed to encode params for web service call."); } catch (ClientProtocolException e) { Log.w(LOG_TAG, e); callback.onFailure("Communication with the web service encountered a protocol exception."); } catch (IOException e) { Log.w(LOG_TAG, e); callback.onFailure("Communication with the web service timed out."); } }
From source file:sdmx.net.service.nsi.Sdmx20NSIQueryable.java
public Reader query2(String action, InputStream in, int length) { HttpClient client = new DefaultHttpClient(); try {/*from w ww .j a v a2 s . c o m*/ HttpPost req = new HttpPost(getServiceURL()); req.setHeader("Content-Type", mediaType); //req.setHeader("Accept","application/xml"); HttpEntity entity = new InputStreamEntity(in, length); req.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(req, responseHandler); int fromIndex = responseBody.indexOf(action, 0); fromIndex = (responseBody.indexOf(">", fromIndex + action.length())) + 1; int toIndex = responseBody.lastIndexOf("</" + action); responseBody = responseBody.substring(fromIndex, toIndex); Reader reader = new StringReader(responseBody); if (SdmxIO.isSaveXml()) { String name = System.currentTimeMillis() + ".xml"; FileOutputStream file = new FileOutputStream(name + ".xml"); IOUtils.copy(reader, file); FileInputStream in2 = new FileInputStream(name + ".xml"); reader = new InputStreamReader(in2); } return reader; } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:com.github.kristofa.test.http.MockHttpServerTest.java
@Test public void testShouldHandleMultipleRequests() throws ClientProtocolException, IOException { // Given a mock server configured to respond to a POST / with data // "Hello World" with an ID // And configured to respond to a GET /test with "Yes sir!" responseProvider.expect(Method.POST, "/", "text/plain; charset=UTF-8", "Hello World").respondWith(200, "text/plain", "ABCD1234"); responseProvider.expect(Method.GET, "/test").respondWith(200, "text/plain", "Yes sir!"); // When a request for POST / arrives final HttpPost req = new HttpPost(baseUrl + "/"); req.setEntity(new StringEntity("Hello World", UTF_8)); ResponseHandler<String> handler = new BasicResponseHandler(); String responseBody = client.execute(req, handler); // Then the response is "ABCD1234" assertEquals("ABCD1234", responseBody); // When a request for GET /test arrives final HttpGet get = new HttpGet(baseUrl + "/test"); handler = new BasicResponseHandler(); responseBody = client.execute(get, handler); // Then the response is "Yes sir!" assertEquals("Yes sir!", responseBody); }
From source file:com.tlabs.eve.HttpClientTest.java
protected String post(String url, final List<NameValuePair> parameters) { HttpClient httpclient = new DefaultHttpClient(connectionManager); try {//from w ww . ja v a 2 s . c om HttpPost post = new HttpPost(url); if ((null != parameters) && (parameters.size() > 0)) { post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); } post.addHeader("content-type", "application/x-www-form-urlencoded"); System.out.println(post.getRequestLine()); String s = httpclient.execute(post, new BasicResponseHandler()); //System.out.println(s); return s; } catch (Exception e) { e.printStackTrace(System.err); //fail(e.getLocalizedMessage()); return null; //throw e; } }
From source file:seava.j4e.web.controller.ui.extjs.DependencyLoader.java
/** * Resolve the dependencies of the given component and returns them in a * list./*from w w w.j a va2 s. c om*/ * * @param cmp * @return * @throws Exception */ private List<String> resolveCmpDependencies(String cmp) throws Exception { String url = this.urlDpd(cmp); HttpGet get = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); List<String> result = null; try { if (logger.isDebugEnabled()) { logger.debug("Calling http request: " + url); } String responseBody = getHttpClient().execute(get, responseHandler); result = getJsonMapper().readValue(responseBody, new TypeReference<List<String>>() { }); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { logger.warn("Cannot find dependencies for component " + cmp + " at " + url); } else { e.printStackTrace(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } get.releaseConnection(); return result; }
From source file:MainFrame.HttpCommunicator.java
public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException { String response = null;//from w w w. j av a 2s . c o m if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.removeLesson", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }