List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER
String RETRY_HANDLER
To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.
Click Source Link
From source file:com.bluexml.side.framework.facetmap.alfrescoConnector.AlfrescoCommunicator.java
private byte[] buildGetMethodAndExecute(String url, Map<String, String> params) { byte[] responseBody = {}; GetMethod get = new GetMethod(url); get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); logger.debug("parameters :" + params); ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { pairs.add(new NameValuePair(entry.getKey(), entry.getValue())); }//from w ww .j av a 2 s . c o m NameValuePair[] arr = new NameValuePair[pairs.size()]; arr = pairs.toArray(arr); get.setQueryString(arr); // Execute the method. int statusCode; try { statusCode = http.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + get.getStatusLine()); } // Read the response body. responseBody = get.getResponseBody(); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Release the connection. get.releaseConnection(); } return responseBody; }
From source file:com.m2a.bean.M2ACountryIPBlockerBean.java
public Object execute() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Executing execute()"); }// w w w. j a v a2s . co m /* * Specific command string for this activity * Generally this will a Stored Procedure name with ? delimited by comma for arguments */ /* * Parameters are to sent to Persistence access layer in the form of Object array */ Object[] parameters = new Object[5]; /* * Data from the form is copied to the DTO set earlier via prepareDto() * getDto() returns Object, hence it has to type casted to specific dto class */ M2ACustomerRegistrationDTO bizDto; bizDto = (M2ACustomerRegistrationDTO) getDto(); /* * Populate the parameter array by reading data from DTO */ String countryCode = (String) getFormMap().get("customerCountryCode"); String ipAddress = (String) getFormMap().get("remoteAddr"); //get licensekey & requesttype from properties String sep = pathSeparator(); String propsPath = System.getProperty("catalina.base") + sep + "deploy" + sep + "M2A.war" + sep + "WEB-INF" + sep + "classes" + sep + "com" + sep + "m2a" + sep + "props" + sep + "ipblocker.props"; File config = new File(propsPath); Properties prop = new Properties(); prop.load(new FileInputStream(config)); String licenseKey = prop.getProperty("ipblocker.licensekey"); String url = prop.getProperty("ipblocker.url"); //String requestType = prop.getProperty("ipblocker.requesttype"); /*MinfraudWebServiceStub minfraudWebServiceStub = new MinfraudWebServiceStub(); Minfraud_soap8 minfraud_soap80 = new Minfraud_soap8(); minfraud_soap80.setCountry(countryCode); minfraud_soap80.setI(ipAddress); minfraud_soap80.setLicense_key(licenseKey); minfraud_soap80.setRequested_type(requestType); Minfraud_soap8Response minfraud_soap8Response = minfraudWebServiceStub.minfraud_soap8(minfraud_soap80); String matchStatus = minfraud_soap8Response.getMinfraud_output().getCountryMatch(); //String matchStatus = "Yes"; System.out.println("****Match Status : "+matchStatus); */ String command = "p_getCountryBlockedIP(?,?,?,?,?)"; if (log.isDebugEnabled()) { log.debug("*** command string value is " + command); } parameters[0] = ipAddress; parameters[1] = countryCode; parameters[2] = new Integer(1); parameters[3] = ""; parameters[4] = ""; ResultList list = new ResultListBase( M2AAccess.findCollection(M2ATokens.APPNAME, bizDto, command, parameters)); String ipCntryCode = ""; if ((list != null) && (list.get(0) != null)) { M2ACustomerRegistrationDTO resultDTO = (M2ACustomerRegistrationDTO) list.get(0); ipCntryCode = resultDTO.getCustomerAddressCountryCode(); } String matchStatus = ""; if (!ipCntryCode.equals("") && countryCode.equals("UK")) { throw new Exception("Please register from the country selected on the registration page"); } else { HttpClient httpClient = new HttpClient(); GetMethod method = null; try { //String url = "http://geoip3.maxmind.com/a"; String queryString = "?l=" + licenseKey + "&i=" + ipAddress; // Create a method instance. method = new GetMethod(url + queryString); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.fatal("\nResponse || Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); matchStatus = new String(responseBody); System.out.println(new String(responseBody)); //matchStatus = "IN"; } finally { // Release the connection. if (method != null) { method.releaseConnection(); } } parameters[0] = ipAddress; parameters[1] = countryCode; parameters[2] = new Integer(2); parameters[3] = matchStatus; parameters[4] = ""; if (!matchStatus.equals(countryCode) && countryCode.equals("UK")) { list = new ResultListBase(M2AAccess.findCollection(M2ATokens.APPNAME, bizDto, command, parameters)); throw new Exception("Please register from the country selected on the registration page"); } } // if(!matchStatus.equals("Yes") && countryCode.equals("UK")){ /** * Persistence layer class M2AAccess.findCollection returns collection of dto objects. * This execute() method must return ProcessResult and ProcessResult holds collection of * data in ResultList class, hence the returned collection has to be wrapped in * ResultList class. */ /** * Got a collection of DTO from access layer * Login result will be only one row ie. one DTO * We need to refer the first DTO only in the processResult * To refer to the first DTO in processAction we need setSingleForm to true */ ProcessResultBase result = new ProcessResultBase(list); result.setSingleForm(true); /** * set as the Client scope */ if (log.isDebugEnabled()) { log.debug("*** Set scope for process ProcessResult to " + M2ATokens.EMPTY); } result.setScope(M2ATokens.EMPTY); return result; }
From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java
/** * It makes a POST towards the gateway/*from www .j av a 2s. c o m*/ * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; log.info("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; log.info("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); log.info("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // log.info("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:fr.esiea.esieaddress.service.login.facebook.FacebookAuthenticationService.java
private String getAccessToken(String code) { /**// w w w . j ava2 s. com * TODO Sheety code change it */ if (!code.isEmpty()) { //If we received a valid code, we can continue to the next step //Next we want to get the access_token from Facebook using the code we got, //use the following url for that, in this url, //client_id-our app id(same as above), redirect_uri-same as above, client_secret-same as //above, code-the code we just got // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. String url = postUrlBase.concat("&code=" + code); GetMethod method = new GetMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response.Use caution: ensure correct character encoding and is // not binary data String responseBodyString = new String(responseBody); LOGGER.info("token : " + responseBodyString); if (responseBodyString.contains("access_token")) { //success String[] mainResponseArray = responseBodyString.split("&"); //like //{"access_token= AAADD1QFhDlwBADrKkn87ZABAz6ZCBQZ//DZD ","expires=5178320"} String accesstoken = ""; for (String string : mainResponseArray) { if (string.contains("access_token")) { return string.replace("access_token=", "").trim(); } } } } catch (IOException e) { LOGGER.error("Fatal transport error", e); } finally { // Release the connection. method.releaseConnection(); } } //failed return ""; }
From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java
/** * It makes a POST towards the gateway//from w w w.jav a 2 s . co m * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java
/** * Constructor./*ww w. j a v a 2s . c o m*/ * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); this.clientHelper = helper; if (requestUri.startsWith("http")) { if (method.equalsIgnoreCase(Method.GET.getName())) { this.httpMethod = new GetMethod(requestUri); } else if (method.equalsIgnoreCase(Method.POST.getName())) { this.httpMethod = new PostMethod(requestUri); } else if (method.equalsIgnoreCase(Method.PUT.getName())) { this.httpMethod = new PutMethod(requestUri); } else if (method.equalsIgnoreCase(Method.HEAD.getName())) { this.httpMethod = new HeadMethod(requestUri); } else if (method.equalsIgnoreCase(Method.DELETE.getName())) { this.httpMethod = new DeleteMethod(requestUri); } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) { final HostConfiguration host = new HostConfiguration(); host.setHost(new URI(requestUri, false)); this.httpMethod = new ConnectMethod(host); } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) { this.httpMethod = new OptionsMethod(requestUri); } else if (method.equalsIgnoreCase(Method.TRACE.getName())) { this.httpMethod = new TraceMethod(requestUri); } else { this.httpMethod = new EntityEnclosingMethod(requestUri) { @Override public String getName() { return method; } }; } this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects()); this.httpMethod.setDoAuthentication(false); if (this.clientHelper.getRetryHandler() != null) { try { this.httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance()); } catch (Exception e) { this.clientHelper.getLogger().log(Level.WARNING, "An error occurred during the instantiation of the retry handler.", e); } } this.responseHeadersAdded = false; setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName())); } else { throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here"); } }
From source file:com.unicauca.braim.http.HttpBraimClient.java
public Session POST_Session(String user_id, String access_token) throws IOException { Session session = null;// w w w . j ava 2 s. c o m Gson gson = new Gson(); String data = "?session[user_id]=" + user_id; String token_data = "&braim_token=" + access_token; PostMethod method = new PostMethod(api_url + "/api/v1/sessions"); method.addParameter("session[user_id]", user_id); method.addParameter("braim_token", access_token); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_CREATED) { System.err.println("Method failed: " + method.getStatusLine()); throw new IOException("The session was not being created"); } byte[] responseBody = method.getResponseBody(); String response = new String(responseBody, "UTF-8"); session = gson.fromJson(response, Session.class); System.out.println("new session of" + session.getUser_id() + "was created"); return session; }
From source file:edu.utah.further.core.ws.HttpUtil.java
/** * Open an HTTP GET method connection to a URL and read the returned response into an * object.// w w w. j a v a2 s . c o m * * @param url * remote URL (usually a web service's URL) * @param httpMethod * HTTP method * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the * response headers and body */ public static HttpResponseTo getHttpResponse(final String url, final HttpMethod method) { if (log.isDebugEnabled()) { log.debug("Sending HTTP " + method + " request to " + url); } // Create an instance of HttpClient. final HttpClient client = new HttpClient(); // Create a method instance. // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false)); try { // Execute the method final int statusCode = client.executeMethod(method); if (statusCode >= 400) { log.error("Method failed: " + method.getStatusLine()); } return new HttpResponseTo(method); } catch (final Throwable e) { if (log.isInfoEnabled()) { log.info("Failed to receive HTTP request from " + url + ": " + e.getMessage()); } } return null; }
From source file:com.ihelpoo.app.api.ApiClient.java
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // HttpClient Cookie,? httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // ??/*from w ww . j av a 2 s .c o m*/ httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION); // ? httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
From source file:com.taobao.ad.easyschedule.action.schedule.ScheduleAction.java
private SchedulerDTO getSchedulerInfo(String instanceName) { SchedulerDTO result = null;//w ww. ja v a 2 s .c o m try { HttpClient client = new HttpClient(); int connTimeout = 1000; client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout); GetMethod getMethod = null; String url = configBO.getStringValue(ConfigDO.CONFIG_KEY_INSTANCE_CONTROL_INTERFACE); url = url.replaceAll("#instance#", instanceName); url = url + "getInstanceAjax"; getMethod = new GetMethod(url); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); int statusCode = client.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { result = JSONObject.parseObject(getMethod.getResponseBodyAsString(), SchedulerDTO.class); } } catch (Exception e) { } return result; }