List of usage examples for org.apache.commons.httpclient HttpClient HttpClient
public HttpClient()
From source file:cn.newtouch.util.HttpClientUtil.java
/** * ?url??post/*w w w. j ava 2s . com*/ * * @param url * @param paramsStr * ? * @param method * @return String ? */ public static String post(String url, String paramsStr, String method) { HttpClient client = new HttpClient(); HttpMethod httpMethod = new PostMethod(url); httpMethod.setQueryString(paramsStr); try { int returnCode = client.executeMethod(httpMethod); if (returnCode == HttpStatus.SC_OK) { return httpMethod.getResponseBodyAsString(); } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); } } catch (Exception e) { System.err.println(e); } finally { httpMethod.releaseConnection(); } return null; }
From source file:mapbuilder.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Get request/*from www . j a v a2 s. c o m*/ */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { if (log.isDebugEnabled()) { Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } // Transfer bytes from in to out log.debug("HTTP GET: transferring..."); //execute the GET String serverUrl = request.getParameter("url"); if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { log.info("GET param serverUrl:" + serverUrl); HttpClient client = new HttpClient(); GetMethod httpget = new GetMethod(serverUrl); client.executeMethod(httpget); if (log.isDebugEnabled()) { Header[] respHeaders = httpget.getResponseHeaders(); for (int i = 0; i < respHeaders.length; ++i) { String headerName = respHeaders[i].getName(); String headerValue = respHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } //dump response to out if (httpget.getStatusCode() == HttpStatus.SC_OK) { //force the response to have XML content type (WMS servers generally don't) response.setContentType("text/xml"); String responseBody = httpget.getResponseBodyAsString().trim(); // use encoding of the request or UTF8 String encoding = request.getCharacterEncoding(); if (encoding == null) encoding = "UTF-8"; response.setCharacterEncoding(encoding); log.info("responseEncoding:" + encoding); // do not set a content-length of the response (string length might not match the response byte size) //response.setContentLength(responseBody.length()); log.info("responseBody:" + responseBody); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } else { log.error("Unexpected failure: " + httpget.getStatusLine().toString()); } httpget.releaseConnection(); } else { throw new ServletException("only HTTP(S) protocol supported"); } } catch (Throwable e) { throw new ServletException(e); } }
From source file:InteractiveAuthenticationExample.java
private void doDemo() throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter(CredentialsProvider.PROVIDER, new ConsoleAuthPrompter()); GetMethod httpget = new GetMethod("http://target-host/requires-auth.html"); httpget.setDoAuthentication(true);/* ww w . j a v a2 s. c om*/ try { // execute the GET int status = client.executeMethod(httpget); // print the status and response System.out.println(httpget.getStatusLine().toString()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } }
From source file:com.cloud.test.regression.Test.java
public boolean executeTest() { int error = 0; Element rootElement = this.getInputFile().get(0).getDocumentElement(); NodeList commandLst = rootElement.getElementsByTagName("command"); //Analyze each command, send request and build the array list of api commands for (int i = 0; i < commandLst.getLength(); i++) { Node fstNode = commandLst.item(i); Element fstElmnt = (Element) fstNode; //new command ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands()); //send a command api.sendCommand(this.getClient(), null); }//from w w w . j a v a 2 s .co m //Try to create portForwarding rule for all available private/public ports ArrayList<String> port = new ArrayList<String>(); for (int j = 1; j < 1000; j++) { port.add(Integer.toString(j)); } //try all public ports for (String portValue : port) { try { s_logger.info("public port is " + portValue); String url = "http://" + this.getParam().get("hostip") + ":8096/?command=createNetworkRule&publicPort=" + portValue + "&privatePort=22&protocol=tcp&isForward=true&securityGroupId=1&account=admin"; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode != 200) { error++; s_logger.error("Can't create portForwarding network rule for the public port " + portValue + ". Request was sent with url " + url); } } catch (Exception ex) { s_logger.error(ex); } } if (error != 0) return false; else return true; }
From source file:gr.upatras.ece.nam.fci.panlab.RepoClient.java
/** * Make a GET call towards the repository. The BASIC Authentication is handled automatically * @param tgwaddr/*w ww. j a v a 2s.co m*/ */ public void execute(String tgwaddr) { String reqRepoURL = repoHostAddress + tgwaddr; HttpClient client = new HttpClient(); // pass our credentials to HttpClient, they will only be used for // authenticating to servers with realm "realm" on the host // "www.verisign.com", to authenticate against an arbitrary realm // or host change the appropriate argument to null. client.getState().setCredentials(new AuthScope(null, 8080), new UsernamePasswordCredentials(username, password)); // create a GET method that reads a file over HTTPS, // we're assuming that this file requires basic // authentication using the realm above. GetMethod get = new GetMethod(reqRepoURL); System.out.println("Request: " + reqRepoURL); get.setRequestHeader("User-Agent", "RepoM2M-1.00"); //get.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Tell the GET method to automatically handle authentication. The // method will use any appropriate credentials to handle basic // authentication requests. Setting this value to false will cause // any request for authentication to return with a status of 401. // It will then be up to the client to handle the authentication. get.setDoAuthentication(true); try { // execute the GET client.executeMethod(get); // print the status and response InputStream responseBody = get.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); //return theinputstream; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // release any connection resources used by the method get.releaseConnection(); } //return null; }
From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java
public String loadCommitMessage(final String url) { final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() { public String call() { final HttpClient client = new HttpClient(); final GetMethod getMethod = new GetMethod(url); try { final int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")"); return getMethod.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); }//from ww w .j av a2s . com } }); ApplicationManager.getApplication().executeOnPooledThread(downloadTask); try { return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { // ignore } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } if (!downloadTask.isDone()) { downloadTask.cancel(true); throw new RuntimeException("Connection timed out"); } return ""; }
From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework. * * @param tc the running test case * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through * @return with Response Holder class.//from ww w.jav a2s . com * @throws IOException in case error occurs * @throws ParserConfigurationException in case error occurs * @throws SAXException in case error occurs */ public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final MultiStubRequestParameters requestParameters) throws IOException, ParserConfigurationException, SAXException { String responseCode; ResponseHolder responseMessage; HttpClient httpClient = new HttpClient(); PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl()); if (requestParameters.isUseProxy()) { httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } createRequest(requestParameters, httpPost); httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer"))); httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.receivebuffer"))); int statusCode; statusCode = httpClient.executeMethod(httpPost); responseCode = "status code: " + statusCode + "\n"; responseMessage = createResponse(httpPost); responseMessage.setResponseCode(responseCode); tc.setActualResponseCode(statusCode); Header contentTypeHeader = httpPost.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { tc.setActualResponseContentType(contentTypeHeader.getValue()); } Header sequenceHeader = httpPost.getResponseHeader("Wilma-Sequence"); if (sequenceHeader != null) { tc.setActualDialogDescriptor(sequenceHeader.getValue()); } return responseMessage; }
From source file:io.hawt.web.JBossPostApp.java
@Test public void testPostWithAuthorizationHeader() throws Exception { System.out.println("Using URL: " + url + " user: " + userName + " password: " + password); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); String userPwd = userName + ":" + password; String hash = new Base64().encodeAsString(userPwd.getBytes()); method.setRequestHeader("Authorization", "Basic " + hash); System.out.println("headers " + Arrays.asList(method.getRequestHeaders())); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); int result = client.executeMethod(method); System.out.println("Status: " + result); String response = method.getResponseBodyAsString(); System.out.println(response); }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java
/** * HEAD methods return an empty response body. If a HEAD request populates * a cache and then a GET follorws, a blank page will result. * This test ensures that the SimplePageCachingFilter implements calculateKey * properly to avoid this problem.// ww w . ja v a 2 s . c om */ public void testHeadThenGetOnCachedPage() throws Exception { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new HeadMethod(buildUrl(cachedPageUrl)); int responseCode = httpClient.executeMethod(httpMethod); //httpclient follows redirects, so gets the home page. assertEquals(HttpURLConnection.HTTP_OK, responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertNull(responseBody); assertNull(httpMethod.getResponseHeader("Content-Encoding")); httpMethod = new GetMethod(buildUrl(cachedPageUrl)); responseCode = httpClient.executeMethod(httpMethod); responseBody = httpMethod.getResponseBodyAsString(); assertNotNull(responseBody); }
From source file:at.ait.dme.yuma.suite.apps.map.server.geo.KMLConverterServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Params: URL of the base map into which KML shall be transformed, URL of the KML String mapUrl = request.getParameter("map"); String kmlUrl = request.getParameter("kml"); if ((mapUrl != null) && (kmlUrl != null)) { // Get KML source file via HTTP GetMethod kmlRequest = new GetMethod(kmlUrl); int responseCode = new HttpClient().executeMethod(kmlRequest); if (responseCode == 200) { try { // Parse KML DOM DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document kml = builder.parse(kmlRequest.getResponseBodyAsStream()); // Instantiate Interpolator ControlPointManager cpm = new ControlPointManager(request, response, mapUrl); AffineTransformation ip = new AffineTransformation(cpm.getControlPoints()); // Convert coordinates in DOM kml = convert(kml, ip);/*from w w w.j av a 2s . c o m*/ // Serialize KML result DOM and return Transformer tf = TransformerFactory.newInstance().newTransformer(); Source source = new DOMSource(kml); Result result = new StreamResult(response.getOutputStream()); tf.transform(source, result); } catch (Exception e) { response.sendError(500, e.getMessage()); return; } } else { response.sendError(500, "KML not found. (Server returned error " + responseCode + ")"); return; } response.setContentType("application/vnd.google-earth.kml+xml"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("done"); } else { response.sendError(404); } }