List of usage examples for org.apache.commons.httpclient HttpClient executeMethod
public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException
From source file:com.thoughtworks.go.agent.launcher.ServerCall.java
public static ServerResponseWrapper invoke(HttpMethod method) throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS); try {/* w ww .j a va2s .c o m*/ final int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_NOT_FOUND) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("Return Code: " + status); out.println("Few Possible Causes: "); out.println("1. Your Go Server is down or not accessible."); out.println( "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent."); out.close(); throw new Exception(sw.toString()); } if (status != HttpStatus.SC_OK) { throw new Exception("Got status " + status + " " + method.getStatusText() + " from server"); } for (Header header : method.getResponseHeaders()) { headers.put(header.getName(), header.getValue()); } return new ServerResponseWrapper(headers, method.getResponseBodyAsStream()); } catch (Exception e) { String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString(); LOG.error(message); throw new Exception(message, e); } finally { method.releaseConnection(); } }
From source file:att.jaxrs.client.Tag.java
public static Tag[] getALLTags() { GetMethod get = new GetMethod(Constants.SELECT_ALL_TAG_OPERATION); TagCollection tag = new TagCollection(); HttpClient httpClient = new HttpClient(); try {//from w w w . j ava2s.co m int result = httpClient.executeMethod(get); System.out.println(Constants.RESPONSE_STATUS_CODE + result); tag = Marshal.unmarshal(TagCollection.class, get.getResponseBodyAsStream()); } catch (IOException e) { e.printStackTrace(); } finally { get.releaseConnection(); } if (null != tag.getTag() && tag.getTag().length > 0) { return tag.getTag(); } else { System.out.println("unmarshalling returned empty collection"); } return null; }
From source file:de.intranda.goobi.plugins.utils.SRUClient.java
/** * Queries the given catalog via Z.3950 (SRU) and returns its response. * //w ww . j ava2 s . com * @param cat The catalog to query. * @param query The query. * @param recordSchema The expected record schema. * @return Query result XML string. */ public static String querySRU(ConfigOpacCatalogue cat, String query, String recordSchema) { String ret = null; if (query != null && !query.isEmpty()) { query = query.trim(); } if (cat != null) { String url = "http://"; url += cat.getAddress(); url += ":" + cat.getPort(); url += "/" + cat.getDatabase(); url += "?version=1.1"; url += "&operation=searchRetrieve"; url += "&query=" + query; url += "&maximumRecords=5"; url += "&recordSchema=" + recordSchema; logger.debug("SRU URL: " + url); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { client.executeMethod(method); ret = method.getResponseBodyAsString(); if (!method.getResponseCharSet().equalsIgnoreCase(ENCODING)) { // If response XML is not UTF-8, re-encode ret = convertStringEncoding(ret, method.getResponseCharSet(), ENCODING); } } catch (HttpException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { method.releaseConnection(); } } return ret; }
From source file:com.netflix.genie.server.util.NetUtil.java
/** * Returns the response from an HTTP GET call if it succeeds, null * otherwise.//w w w . j av a 2 s . c o m * * @param uri The URI to execute the HTTP GET on * @return response from an HTTP GET call if it succeeds, null otherwise * @throws IOException if there was an error with the HTTP request */ private static String httpGet(final String uri) throws IOException { String response = null; //TODO: Use one of other http clients to remove dependency final HttpClient client = new HttpClient(); final HttpMethod method = new GetMethod(uri); client.executeMethod(method); final int status = method.getStatusCode(); if (status == HttpURLConnection.HTTP_OK) { response = method.getResponseBodyAsString(); } return response; }
From source file:att.jaxrs.client.Content.java
public static Content[] getContents() { // Sent HTTP GET request to query Content table GetMethod get = new GetMethod(Constants.SELECT_ALL_CONTENT_OPERATION); ContentCollection collection = new ContentCollection(); HttpClient httpClient = new HttpClient(); try {/* w w w. j ava2 s . c o m*/ int result = httpClient.executeMethod(get); System.out.println(Constants.RESPONSE_STATUS_CODE + result); collection = Marshal.unmarshal(ContentCollection.class, get.getResponseBodyAsStream()); } catch (IOException e) { e.printStackTrace(); } finally { get.releaseConnection(); } if (null != collection.getContents() && collection.getContents().length > 0) { return collection.getContents(); } else { System.out.println("unmarshalling returned empty collection"); } return null; }
From source file:com.cloud.test.longrun.PerformanceWithAPI.java
private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort, String privatePort) throws IOException { String encodedPrivateIp = URLEncoder.encode("" + privateIp, "UTF-8"); String encodedPublicIp = URLEncoder.encode("" + publicIp, "UTF-8"); String encodedPrivatePort = URLEncoder.encode("" + privatePort, "UTF-8"); String encodedPublicPort = URLEncoder.encode("" + publicPort, "UTF-8"); String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8"); int responseCode = 500; String requestToSign = "apiKey=" + encodedApiKey + "&command=createOrUpdateIpForwardingRule&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort; requestToSign = requestToSign.toLowerCase(); s_logger.info("Request to sign is " + requestToSign); String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule" + "&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort + "&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey + "&signature=" + encodedSignature;//from w w w. j a v a 2s . c o m s_logger.info("Trying to create IP forwarding rule: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("create ip forwarding rule response code: " + responseCode); if (responseCode == 200) { s_logger.info("The rule is created successfully"); } else if (responseCode == 500) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorCode", "description" }); s_logger.error("create ip forwarding rule (linux) test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description")); } else { s_logger.error("internal error processing request: " + method.getStatusText()); } return responseCode; }
From source file:edu.stanford.muse.webapp.HTMLToImage.java
/** * Convert an HTML page at the specified URL into an image who's data is * written to the provided output stream. * * @param url URL to the page that is to be imaged. * @param os An output stream that is to be opened for writing. Image * data will be written to the provided stream. The stream * will not be closed under any circumstances by this method. * @param width The desired width of the image that will be created. * @param height The desired height of the image that will be created. * * @returns true if the page at the provided URL was loaded, converted to an * image, and the image data has been written to the output stream, * false if an error has ocurred along the way. * * @throws HTMLImagerException if an error has ocurred. *//* w ww . j a v a 2s . c o m*/ public static boolean image(String url, OutputStream os, int width, int height) { if (log.isDebugEnabled()) log.debug("Imaging url '" + url + "'."); boolean successful = false; try { HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); httpClient.executeMethod(getMethod); int httpStatus = getMethod.getStatusCode(); if (httpStatus == HttpServletResponse.SC_OK) { Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setXHTML(true); tidy.setHideComments(true); tidy.setInputEncoding("UTF-8"); tidy.setOutputEncoding("UTF-8"); tidy.setShowErrors(0); tidy.setShowWarnings(false); Document doc = tidy.parseDOM(getMethod.getResponseBodyAsStream(), null); if (doc != null) { BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) buf.getGraphics(); Graphics2DRenderer renderer = new Graphics2DRenderer(); SharedContext context = renderer.getSharedContext(); UserAgentCallback userAgent = new HTMLImagerUserAgent(url); context.setUserAgentCallback(userAgent); context.setNamespaceHandler(new XhtmlNamespaceHandler()); renderer.setDocument(doc, url); renderer.layout(graphics, new Dimension(width, height)); renderer.render(graphics); graphics.dispose(); /* JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam( buf ); param.setQuality( (float)1.0, false ); JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder( os, param ); imageEncoder.encode( buf ); */ successful = true; } else { if (log.isDebugEnabled()) log.debug("Unable to image URL '" + url + "'. The HTML that was returned could not be tidied."); } } else { if (log.isDebugEnabled()) log.debug("Unable to image URL '" + url + "'. Server returned status code '" + httpStatus + "'."); } } catch (Exception e) { throw new RuntimeException("Unable to image URL '" + url + "'.", e); } return successful; }
From source file:net.cbtltd.server.WebService.java
/** * Gets the HTTP response.//from w w w. j a v a2 s. c om * * @param url the url of the service. * @param nameids the parameter key value pairs. * @return the HTTP response string. * @throws Throwable the exception that can be thrown. */ public static final String getHttpResponse(String url, NameId[] nameids) throws Throwable { GetMethod get = new GetMethod(url); get.addRequestHeader("Accept", "text/plain"); HttpMethodParams params = new HttpMethodParams(); get.setParams(params); for (NameId nameid : nameids) { params.setParameter(nameid.getId(), nameid.getName()); } HttpClient httpclient = new HttpClient(); int rs = httpclient.executeMethod(get); LOG.debug("rs=" + rs + " " + get.getResponseBodyAsString()); return get.getResponseBodyAsString(); }
From source file:com.intellij.diagnostic.DevelopersLoader.java
public static Collection<Developer> fetchDevelopers(ProgressIndicator indicator) throws IOException { List<Developer> developers = new LinkedList<Developer>(); developers.add(Developer.NULL);//from w w w. ja v a2s. com HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT); HttpMethod method = new GetMethod(DEVELOPERS_LIST_URL); try { client.executeMethod(method); BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), DATA_CHARSET)); try { while (true) { String line = reader.readLine(); if (line == null) break; int i = line.indexOf('\t'); if (i == -1) throw new IOException("Protocol error"); int id = Integer.parseInt(line.substring(0, i)); String name = line.substring(i + 1); developers.add(new Developer(id, name)); indicator.checkCanceled(); } return developers; } finally { reader.close(); } } finally { method.releaseConnection(); } }
From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java
private static int executeHttpMethod(HttpMethod method) throws Exception { HttpClient client = new HttpClient(); int statusCode; try {//from w ww . ja v a 2s . c om statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { JSONObject result = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); if (result.has("error-code")) { String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"), result.getString("stacktrace") }; throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: " + method.getStatusLine() + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]); } } return statusCode; } catch (Exception e) { throw e; } finally { method.releaseConnection(); } }