List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString
public abstract String getResponseBodyAsString() throws IOException;
From source file:org.openoffice.maven.it.FitRunner.java
/** * Read.//from w w w . j a v a2s . c om * * @param uri the uri * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private String read(URI uri) throws IOException { if (uri.getScheme().startsWith("file")) { return read(new File(uri)); } HttpClient client = new HttpClient(); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpMethod method = new GetMethod(uri.toString()); int statusCode = client.executeMethod(method); String content = method.getResponseBodyAsString(); method.releaseConnection(); if (statusCode != HttpStatus.SC_OK) { throw new IOException(uri + " returned with " + statusCode); } return content; }
From source file:org.openqa.selenium.remote.HttpCommandExecutor.java
private Response createResponse(HttpMethod httpMethod) throws Exception { Response response;//from www . j a v a2s . c om Header header = httpMethod.getResponseHeader("Content-Type"); if (header != null && header.getValue().startsWith("application/json")) { response = new JsonToBeanConverter().convert(Response.class, httpMethod.getResponseBodyAsString()); } else { response = new Response(); if (header != null && header.getValue().startsWith("image/png")) { response.setValue(httpMethod.getResponseBody()); } else { response.setValue(httpMethod.getResponseBodyAsString()); } String uri = httpMethod.getURI().toString(); int sessionIndex = uri.indexOf("/session/"); if (sessionIndex != -1) { sessionIndex += "/session/".length(); int nextSlash = uri.indexOf("/", sessionIndex); if (nextSlash != -1) { response.setSessionId(uri.substring(sessionIndex, nextSlash)); response.setContext("foo"); } } } response.setError(!(httpMethod.getStatusCode() > 199 && httpMethod.getStatusCode() < 300)); if (response.getValue() instanceof String) { //We normalise to \n because Java will translate this to \r\n //if this is suitable on our platform, and if we have \r\n, java will //turn this into \r\r\n, which would be Bad! response.setValue(((String) response.getValue()).replace("\r\n", "\n")); } return response; }
From source file:org.openrdf.http.client.HTTPClient.java
public void sendUpdate(QueryLanguage ql, String update, String baseURI, Dataset dataset, boolean includeInferred, Binding... bindings) throws IOException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { HttpMethod method = getUpdateMethod(ql, update, baseURI, dataset, includeInferred, bindings); try {/*from w w w .j ava 2s .c o m*/ int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (!is2xx(httpCode)) { ErrorInfo errInfo = ErrorInfo.parse(method.getResponseBodyAsString()); if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else { throw new RepositoryException("Failed to execute update: " + errInfo); } } } finally { releaseConnection(method); } }
From source file:org.openrdf.http.client.HTTPClient.java
public String getNamespace(String prefix) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();/*w ww . jav a2 s .c om*/ HttpMethod method = new GetMethod(Protocol.getNamespacePrefixLocation(repositoryURL, prefix)); setDoAuthentication(method); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { return method.getResponseBodyAsString(); } else if (httpCode == HttpURLConnection.HTTP_NOT_FOUND) { return null; } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException("Failed to get namespace: " + errInfo + " (" + httpCode + ")"); } } finally { releaseConnection(method); } }
From source file:org.openrdf.http.client.HTTPClient.java
public long size(Resource... contexts) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();//from w w w . j ava 2s . c om String[] encodedContexts = Protocol.encodeContexts(contexts); NameValuePair[] contextParams = new NameValuePair[encodedContexts.length]; for (int i = 0; i < encodedContexts.length; i++) { contextParams[i] = new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContexts[i]); } HttpMethod method = new GetMethod(Protocol.getSizeLocation(repositoryURL)); setDoAuthentication(method); method.setQueryString(contextParams); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String response = method.getResponseBodyAsString(); try { return Long.parseLong(response); } catch (NumberFormatException e) { throw new RepositoryException("Server responded with invalid size value: " + response); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException(errInfo.toString()); } } finally { releaseConnection(method); } }
From source file:org.openrdf.http.client.HTTPClient.java
protected ErrorInfo getErrorInfo(HttpMethod method) throws RepositoryException { try {//from w ww .j a v a2 s .co m ErrorInfo errInfo = ErrorInfo.parse(method.getResponseBodyAsString()); logger.warn("Server reports problem: {}", errInfo.getErrorMessage()); return errInfo; } catch (IOException e) { logger.warn("Unable to retrieve error info from server"); throw new RepositoryException("Unable to retrieve error info from server", e); } }
From source file:org.owtf.runtime.core.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;//ww w . j ava 2s . com case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // Do this after setting the headers so the length is corrected RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\n" + arrayToStr(method.getResponseHeaders()); // httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000)); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.paxle.se.provider.rsssearch.impl.gui.ConfigServlet.java
@Override public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { Template template = null;/* w w w . j a va 2s.c o m*/ try { template = this.getTemplate("/resources/templates/config.vm"); if (request.getMethod().equals("POST")) { if (request.getParameter("opensearchurl") != null) { String url = request.getParameter("opensearchurl"); this.addRssUrlFromOpensearchXMLUrl(url); } else if (request.getParameter("opensearchhtmlurl") != null) { HttpMethod hm = null; try { hm = new GetMethod(request.getParameter("opensearchhtmlurl")); HttpClient hc = new HttpClient(); int status = hc.executeMethod(hm); if (status == 200) { Page page = new Page(hm.getResponseBodyAsString()); page.setUrl(request.getParameter("opensearchhtmlurl")); Parser parser = new Parser(new Lexer(page)); parser.setNodeFactory(new PrototypicalNodeFactory()); OpenSearchLinkCollector oslc = new OpenSearchLinkCollector(); parser.visitAllNodesWith(oslc); if (oslc.found()) { this.addRssUrlFromOpensearchXMLUrl(oslc.getURL()); } page.close(); } } finally { if (hm != null) hm.releaseConnection(); } } } if (request.getParameter("urls") != null) { String[] new_urls = request.getParameter("urls").split("\n"); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < new_urls.length; i++) if (!new_urls[i].equals("")) list.add(new_urls[i].trim()); this.pManager.setUrls(list); this.pManager.registerSearchers(list); } List<String> urls = this.pManager.getUrls(); context.put("urls", urls); } catch (Exception e) { logger.warn("Unexpected Error:", e); } return template; }
From source file:org.pentaho.di.cluster.HttpUtil.java
public static String execService(VariableSpace space, String hostname, String port, String webAppName, String serviceAndArguments, String username, String password, String proxyHostname, String proxyPort, String nonProxyHosts) throws Exception { // Prepare HTTP get ///*from www. j a v a 2 s . c o m*/ HttpClient client = SlaveConnectionManager.getInstance().createHttpClient(); addCredentials(client, space, hostname, port, webAppName, username, password); addProxy(client, space, hostname, proxyHostname, proxyPort, nonProxyHosts); String urlString = constructUrl(space, hostname, port, webAppName, serviceAndArguments); HttpMethod method = new GetMethod(urlString); // Execute request // InputStream inputStream = null; BufferedInputStream bufferedInputStream = null; try { int result = client.executeMethod(method); if (result != 200) { throw new KettleException("Response code " + result + " received while querying " + urlString); } // the response String body = method.getResponseBodyAsString(); return body; } finally { if (bufferedInputStream != null) { bufferedInputStream.close(); } if (inputStream != null) { inputStream.close(); } // Release current connection to the connection pool once you are done method.releaseConnection(); } }
From source file:org.pentaho.di.trans.dataservice.jdbc.RemoteClient.java
HttpMethod execMethod(HttpMethod method) throws SQLException { try {//from w w w . j av a 2 s.co m int result = client.executeMethod(method); if (result == 500) { throw new SQLException("There was an error reading data from the server."); } if (result == 401) { throw new SQLException( "Nice try-but we couldn't log you in. Check your username and password and try again."); } if (result != 200) { throw new SQLException(method.getResponseBodyAsString()); } } catch (IOException e) { throw new SQLException( "You don't seem to be getting a connection to the server. Check the host and port you're using and make sure the sever is up and running."); } return method; }