List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests.//from www . j a v a2 s.com * * @return <code>true</code> if login was successful; <code>false</code> otherwise. */ public boolean doLogin() { 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.warn("Method failed: " + method.getStatusLine()); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } try { final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (Exception e) { logger.error("Parsing response failed"); } } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * /*from w w w . j av a 2s . c om*/ * Typically used for changing parameters. * * @param REST * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) { // 3 retries upon failure for (int i = 0; i < 3; 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(3, 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; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } 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.openhab.binding.garadget.internal.Connection.java
/** * Send a command to the Particle REST API (convenience function). * * @param device/*from www .j a v a 2 s .c om*/ * the device context, or <code>null</code> if not needed for this command. * @param funcName * the function name to call, or variable/field to retrieve if <code>command</code> is * <code>null</code>. * @param user * the user name to use in Basic Authentication if the funcName would require Basic Authentication. * @param pass * the password to use in Basic Authentication if the funcName would require Basic Authentication. * @param command * the command to send to the API. * @param proc * a callback object that receives the status code and response body, or <code>null</code> if not * needed. */ public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) { String url = null; String httpMethod = null; String content = null; String contentType = null; Properties headers = new Properties(); logger.trace("sendCommand: funcName={}", funcName); switch (funcName) { case "createToken": httpMethod = HTTP_POST; url = TOKEN_URL; content = command; contentType = APPLICATION_FORM_URLENCODED; break; case "deleteToken": httpMethod = HTTP_DELETE; url = String.format(ACCESS_TOKENS_URL, tokens.accessToken); break; case "getDevices": httpMethod = HTTP_GET; url = String.format(GET_DEVICES_URL, tokens.accessToken); break; default: url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken); if (command == null) { // retrieve a variable httpMethod = HTTP_GET; } else { // call a function httpMethod = HTTP_POST; content = command; contentType = APPLICATION_JSON; } break; } HttpClient client = new HttpClient(); // Only perform basic authentication when we aren't using OAuth if (!url.contains("access_token=")) { Credentials credentials = new UsernamePasswordCredentials(user, pass); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } HttpMethod method = createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : headers.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey))); logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey)); } try { // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null)); logger.trace("content='{}', contentType='{}'", content, contentType); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug(e.getMessage()); } } int statusCode = client.executeMethod(method); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { logger.debug("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("Body of response: {}", responseBody); } if (proc != null) { proc.handleResponse(statusCode, responseBody); } } catch (HttpException he) { logger.warn("{}", he); } catch (IOException ioe) { logger.debug("{}", ioe); } finally { method.releaseConnection(); } }
From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL. * //from ww w. jav a2 s. c om * @param httpMethod * the HTTP method to use * @param url * the url to execute (in milliseconds) * @param contentString * the content to be sent to the given <code>url</code> or <code>null</code> if no content should be * sent. * @param contentType * the content type of the given <code>contentString</code> * @return the response body or <code>NULL</code> when the request went wrong */ protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) { HttpClient client = new HttpClient(); HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(HTTP_REQUEST_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey))); } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && contentString != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; InputStream content = new ByteArrayInputStream(contentString.getBytes()); eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } if (logger.isDebugEnabled()) { try { logger.trace("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.trace(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } // Manually handle 307 redirects with a little tail recursion if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { Header[] headers = method.getResponseHeaders("Location"); String newUrl = headers[headers.length - 1].getValue(); return executeUrl(httpMethod, newUrl, contentString, contentType); } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.trace("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.trace("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.trace(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.openhab.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * /*from w w w. ja va 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_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.debug("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.debug("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); 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.openmicroscopy.shoola.svc.proxy.Reply.java
/** * Checks the status of the response.//from w w w.java 2 s . c o m * * @param response The response to handle. * @return The message from server. * @throws TransportException If an error occurred while transferring data. */ protected static String checkStatusCode(HttpMethod response) throws TransportException { int status = response.getStatusCode(); if (status != -1) {//HttpStatus.SC_OK) { Reader reader = null; try { reader = new InputStreamReader(response.getResponseBodyAsStream()); char[] buf = new char[32678]; StringBuilder str = new StringBuilder(); for (int n; (n = reader.read(buf)) != -1;) str.append(buf, 0, n); try { if (reader != null) reader.close(); } catch (Exception ex) { } return str.toString(); } catch (Exception e) { try { if (reader != null) reader.close(); } catch (Exception ex) { } throw new TransportException("Couldn't handle request: " + HttpStatus.getStatusText(status) + "."); } } return null; }
From source file:org.openrdf.http.client.HTTPClient.java
protected void getTupleQueryResult(HttpMethod method, TupleQueryResultHandler handler) throws IOException, TupleQueryResultHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys(); if (tqrFormats.isEmpty()) { throw new RepositoryException("No tuple query result parsers have been registered"); }/*ww w . j av a2 s . c o m*/ for (TupleQueryResultFormat format : tqrFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredTQRFormat != null && !preferredTQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2; } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam); } } int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String mimeType = getResponseMIMEType(method); try { TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats); TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory()); parser.setTupleQueryResultHandler(handler); parser.parse(method.getResponseBodyAsStream()); } catch (UnsupportedQueryResultFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (QueryResultParseException e) { throw new RepositoryException("Malformed query result from server", e); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) { throw new QueryInterruptedException(); } else { ErrorInfo errInfo = getErrorInfo(method); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) { throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage()); } else { throw new RepositoryException(errInfo.toString()); } } }
From source file:org.openrdf.http.client.HTTPClient.java
protected void getRDF(HttpMethod method, RDFHandler handler, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); }/* www. j ava 2 s .c om*/ List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, preferredRDFFormat); for (String acceptParam : acceptParams) { method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam); } int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String mimeType = getResponseMIMEType(method); try { RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); parser.setRDFHandler(handler); parser.parse(method.getResponseBodyAsStream(), method.getURI().getURI()); } catch (UnsupportedRDFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (RDFParseException e) { throw new RepositoryException("Malformed query result from server", e); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) { throw new QueryInterruptedException(); } else { ErrorInfo errInfo = getErrorInfo(method); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) { throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage()); } else { throw new RepositoryException(errInfo.toString()); } } }
From source file:org.openrdf.http.client.HTTPClient.java
protected boolean getBoolean(HttpMethod method) throws IOException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<BooleanQueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys(); if (booleanFormats.isEmpty()) { throw new RepositoryException("No boolean query result parsers have been registered"); }/*from ww w .j a va2 s . c o m*/ for (BooleanQueryResultFormat format : booleanFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2; } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam); } } int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String mimeType = getResponseMIMEType(method); try { BooleanQueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats); BooleanQueryResultParser parser = QueryResultIO.createParser(format); return parser.parse(method.getResponseBodyAsStream()); } catch (UnsupportedQueryResultFormatException e) { throw new RepositoryException("Server responded with an unsupported file format: " + mimeType); } catch (QueryResultParseException e) { throw new RepositoryException("Malformed query result from server", e); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) { throw new QueryInterruptedException(); } else { ErrorInfo errInfo = getErrorInfo(method); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) { throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage()); } else { throw new RepositoryException(method.getStatusText()); } } }
From source file:org.openrdf.repository.sparql.query.SPARQLBooleanQuery.java
public boolean evaluate() throws QueryEvaluationException { try {//from w w w .jav a 2 s .c o m boolean complete = false; HttpMethod response = getResponse(); try { boolean result = parser.parse(response.getResponseBodyAsStream()); complete = true; return result; } catch (HttpException e) { throw new QueryEvaluationException(e); } catch (QueryResultParseException e) { throw new QueryEvaluationException(e); } finally { if (!complete) { response.abort(); } } } catch (IOException e) { throw new QueryEvaluationException(e); } }