List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine
public abstract StatusLine getStatusLine();
From source file:org.colombbus.tangara.net.TConnection.java
public synchronized Document sendCommand(Command cmd) throws CommandException { HttpMethod method = createMethod(cmd); Document doc = null;/*from w w w .ja v a 2s .co m*/ try { String logMsg = String.format("Prepare executing method %s", //$NON-NLS-1$ method.getPath()); LOG.info(logMsg); String httpResponse = executeMethod(method); doc = buildXmlResponse(method, httpResponse); logMsg = String.format("Method succeed %s %s", //$NON-NLS-1$ method.getPath(), method.getStatusLine().toString()); LOG.info(logMsg); } catch (CommandException cmdEx) { LOG.error("Command excetion catched in the command", cmdEx);//$NON-NLS-1$ throw cmdEx; } catch (Throwable th) { LOG.error("Unknown error catched in the command", th);//$NON-NLS-1$ throw new CommandException(method.getPath(), CommandException.UNKNOWN_ERR, "Unknown error catched in the command", th);//$NON-NLS-1$ } finally { method.releaseConnection(); } return doc; }
From source file:org.eclipse.mylyn.github.internal.GitHubService.java
private void executeMethod(HttpMethod method) throws GitHubServiceException { int status;/*from www . j ava 2s.c o m*/ try { status = httpClient.executeMethod(method); } catch (HttpException e) { throw new GitHubServiceException(e); } catch (IOException e) { throw new GitHubServiceException(e); } if (status != HttpStatus.SC_OK) { switch (status) { case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new PermissionDeniedException(method.getStatusLine()); default: throw new GitHubServiceException(method.getStatusLine()); } } }
From source file:org.eclipse.scada.hd.exporter.http.client.HdHttpClient.java
public List<DataPoint> getData(final String item, final String type, final Date from, final Date to, final Integer number) throws Exception { final HttpClient client = new HttpClient(); final HttpMethod method = new GetMethod( this.baseUrl + "/" + URLEncoder.encode(item, "UTF-8") + "/" + URLEncoder.encode(type, "UTF-8") + "?from=" + URLEncoder.encode(Utils.isoDateFormat.format(from), "UTF-8") + "&to=" + URLEncoder.encode(Utils.isoDateFormat.format(to), "UTF-8") + "&no=" + number); client.getParams().setSoTimeout((int) this.timeout); try {//from w w w. j a v a 2 s . co m final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new RuntimeException("Method failed with error " + status + " " + method.getStatusLine()); } return Utils.fromJson(method.getResponseBodyAsString()); } finally { method.releaseConnection(); } }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests.//from w ww.j a va2s. co m * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Communication with radio failed: " + method.getStatusLine()); if (method.getStatusCode() == 403) { throw new RuntimeException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (HttpException he) { logger.debug("Fatal protocol violation: {}", he.toString()); throw he; } catch (IOException ioe) { logger.debug("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * * Typically used for changing parameters. * * @param REST/*from ww w . j a va 2 s.c om*/ * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result * @throws IOException if the request failed. */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException { // 3 retries upon failure for (int i = 0; i < 2; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '" + url + "'"); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); isLoggedIn = false; method.releaseConnection(); continue; } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("got result: " + responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; method.releaseConnection(); continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { return result; } isLoggedIn = false; method.releaseConnection(); continue; // try again } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); isLoggedIn = false; throw he; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * //from w ww. j a v a 2 s.c o m * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.genemania.util.HttpRetriever.java
private String fetchPage(String url) { String ret = ""; try {// w ww .j av a 2s. c o m HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("HttpRetriever error: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); method.releaseConnection(); ret = new String(responseBody); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:org.gss_project.gss.web.client.TestClient.java
public static void main(String[] args) { String user = "ebstest@grnet-hq.admin.grnet.gr"; String token = "PcxaZ/4oIqCqIvCYgsUcKr1hAFcsW40G3kcWJSRPJV5GjzoNuo8RsA=="; String host = "pithos.grnet.gr"; String restPath = "/pithos/rest"; String path = "/" + user + "/files/"; String now = DateUtil.formatDate(new Date()); String signature = sign("GET", now, path, token); HttpClient client = new HttpClient(); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost(host);/*from w ww. j av a2 s . co m*/ HttpMethod method = new GetMethod(restPath + path); Collection<Header> headers = new ArrayList<Header>(); Header auth = new Header("Authorization", user + " " + signature); headers.add(auth); Header date = new Header("X-GSS-Date", now); headers.add(date); System.out.println(headers.toString()); hostconfig.getParams().setParameter("http.default-headers", headers); try { // Execute the method. int statusCode = client.executeMethod(hostconfig, method); if (statusCode != HttpStatus.SC_OK) System.err.println("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 System.out.println(new String(responseBody)); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:org.infoglue.cms.applications.managementtool.actions.UploadPortletAction.java
/** * Report to deliver engines that a portlet has been uploaded * * @param contentId/* ww w .j a va 2s.com*/ * contentId of portlet */ private void updateDeliverEngines(Integer digitalAssetId) { List allUrls = CmsPropertyHandler.getInternalDeliveryUrls(); allUrls.addAll(CmsPropertyHandler.getPublicDeliveryUrls()); Iterator urlIterator = allUrls.iterator(); while (urlIterator.hasNext()) { String url = (String) urlIterator.next() + "/DeployPortlet.action"; try { HttpClient client = new HttpClient(); // establish a connection within 5 seconds client.setConnectionTimeout(5000); // set the default credentials HttpMethod method = new GetMethod(url); method.setQueryString("digitalAssetId=" + digitalAssetId); method.setFollowRedirects(true); // execute the method client.executeMethod(method); StatusLine status = method.getStatusLine(); if (status != null && status.getStatusCode() == 200) { log.info("Successfully deployed portlet at " + url); } else { log.warn("Failed to deploy portlet at " + url + ": " + status); } //clean up the connection resources method.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } } /* Properties props = CmsPropertyHandler.getProperties(); for (Enumeration keys = props.keys(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); if (key.startsWith(PORTLET_DEPLOY_PREFIX)) { String url = props.getProperty(key); try { HttpClient client = new HttpClient(); //establish a connection within 5 seconds client.setConnectionTimeout(5000); //set the default credentials HttpMethod method = new GetMethod(url); method.setQueryString("digitalAssetId=" + digitalAssetId); method.setFollowRedirects(true); //execute the method client.executeMethod(method); StatusLine status = method.getStatusLine(); if (status != null && status.getStatusCode() == 200) { log.info("Successfully deployed portlet at " + url); } else { log.warn("Failed to deploy portlet at " + url + ": " + status); } //clean up the connection resources method.releaseConnection(); } catch (Throwable e) { log.error(e.getMessage(), e); } } } */ }
From source file:org.j2free.http.HttpCallResult.java
/** * /*w w w . j a va2 s.c om*/ * @param method * @throws IOException */ public HttpCallResult(HttpMethod method) throws IOException { this.method = method; this.response = method.getResponseBodyAsString(); this.bytes = method.getResponseBody(); requestHeaders = new HashMap(); responseHeaders = new HashMap(); Header[] headers = method.getRequestHeaders(); for (Header header : headers) { requestHeaders.put(header.getName(), header); } headers = method.getResponseHeaders(); for (Header header : headers) { responseHeaders.put(header.getName(), header); } status = method.getStatusLine(); }