Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:com.wfreitas.camelsoap.util.ClientWsdlLoader.java

public InputStream load(String url) throws Exception {
    GetMethod httpGetMethod;//from  w  w  w.  java  2  s.co  m

    if (url.startsWith("file")) {
        return new URL(url).openStream();
    }

    // Authentication is not being overridden on the method.  It needs
    // to be present on the supplied HttpClient instance!
    httpGetMethod = new GetMethod(url);
    httpGetMethod.setDoAuthentication(true);

    try {
        int result = httpClient.executeMethod(httpGetMethod);

        if (result != HttpStatus.SC_OK) {
            if (result < 200 || result > 299) {
                throw new HttpException(
                        "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'.");
            } else {
                logger.warn("Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'.");
            }
        }

        return new ByteArrayInputStream(httpGetMethod.getResponseBody());
    } finally {
        httpGetMethod.releaseConnection();
    }
}

From source file:at.ait.dme.yuma.suite.apps.map.server.geo.MapMetadataServiceImpl.java

@Override
public MapMetadata getMetadata(String url) {
    try {/*from  w w  w. ja  va2 s .  c om*/
        GetMethod getMetadata = new GetMethod(url);
        int statusCode = new HttpClient().executeMethod(getMetadata);
        if (statusCode == HttpStatus.SC_OK) {
            return fromXML(getMetadata.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        logger.info("No metadata found for " + url + " (" + e.getClass() + ")");
    }
    return null;
}

From source file:com.zimbra.qa.unittest.TestWsdlServlet.java

String doWsdlServletRequest(String wsdlUrl, boolean admin, int expectedCode) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;//from  w  ww. j av a  2s.  c o  m
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);

    String url = protoHostPort + wsdlUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        ZimbraLog.test.debug("respCode=" + respCode);
        ZimbraLog.test.debug("statusCode=" + statusCode);
        ZimbraLog.test.debug("statusLine=" + statusLine);

        assertTrue("Response code", respCode == expectedCode);
        assertTrue("Status code", statusCode == expectedCode);

        Header[] respHeaders = method.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            String header = respHeaders[i].toString();
            ZimbraLog.test.debug("ResponseHeader:" + header);
        }

        String respBody = method.getResponseBodyAsString();
        // ZimbraLog.test.debug("Response Body:" + respBody);
        return respBody;

    } catch (HttpException e) {
        fail("Unexpected HttpException" + e);
        throw e;
    } catch (IOException e) {
        fail("Unexpected IOException" + e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.predic8.membrane.core.interceptor.AdjustContentLengthIntegrationTest.java

private GetMethod getMonitoredRequest() {
    GetMethod get = new GetMethod("http://localhost:3010/samples/sqlrest/CUSTOMER/7/");
    return get;
}

From source file:fr.msch.wissl.server.TestIndexer.java

public void test() throws Exception {
    HttpClient client = new HttpClient();

    // /indexer/status as user: 401
    GetMethod get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);//from w ww  .  ja  v a 2 s . c om
    Assert.assertEquals(401, get.getStatusCode());

    // /indexer/status as admin: 200
    get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    // won't try to check the actual content of this object,
    // since I can't predict easily and accurately if 
    // the Indexer will be in Running or Sleeping state at a given time.
    assertTrue(obj.has("running"));
    assertTrue(obj.has("percentDone"));
    assertTrue(obj.has("secondsLeft"));
    assertTrue(obj.has("songsDone"));
    assertTrue(obj.has("songsTodo"));

    // /indexer/rescan as user: 401
    PostMethod post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /indexer/rescan as amdin
    post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // /folders as user: 401
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

    // /folders/listing as user: 401
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders/listing on some file that does not exist: 404
    get = new GetMethod(URL + "folders/listing?directory=/does/not/exist");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    File exp_home = new File(System.getProperty("user.home"));

    // /folders/listing with no arg: homedir
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File dir = new File(obj.getString("directory"));
    assertEquals(exp_home.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(exp_home.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    assertTrue(obj.getJSONArray("listing").length() > 0);

    // /folders/listing with arg '$ROOT'
    get = new GetMethod(URL + "folders/listing?directory=$ROOT");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File[] dirs = File.listRoots();
    assertEquals("", obj.getString("directory"));
    assertEquals("$ROOT", obj.getString("parent"));
    JSONArray arr = obj.getJSONArray("listing");
    HashSet<String> hs = new HashSet<String>(arr.length());
    for (int i = 0; i < arr.length(); i++) {
        hs.add(new File(arr.getString(i)).getAbsolutePath());
    }
    for (File d : dirs) {
        // on windows, listRoots returns a bunch of drive names that don't exist
        if (d.exists()) {
            assertTrue(hs.remove(d.getAbsolutePath()));
        }
    }
    assertTrue(hs.isEmpty());

    // lists test resources folder
    File f = new File("src/test/resources/data2");
    get = new GetMethod(URL + "folders/listing?directory=" + URIUtil.encodeQuery(f.getAbsolutePath()));
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    dir = new File(obj.getString("directory"));
    assertEquals(f.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(f.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    dirs = dir.listFiles();
    arr = obj.getJSONArray("listing");
    assertEquals(2, arr.length());
    assertEquals(new File("src/test/resources/data2/sub1").getAbsolutePath(), arr.get(0));
    assertEquals(new File("src/test/resources/data2/sub2").getAbsolutePath(), arr.get(1));

    // /folders/add as user: 401
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/add : directory does not exist: 404
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(404, post.getStatusCode());

    // /folders/add : not a directory: 400
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", new File("src/test/resources/data/1.mp3").getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/add "/src/test/resources/data"
    f = new File("src/test/resources/data");
    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);
    rt.albumCount.set(5);
    rt.artistCount.set(2);
    rt.playlistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(15);
    rt.downloaded.set(0);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(f.getAbsolutePath(), obj.getJSONArray("folders").getString(0));

    // /folders/add "/src/test/resources/data2/sub1"
    f = new File("src/test/resources/data2/sub1");
    rt.songCount.addAndGet(3);
    rt.albumCount.addAndGet(1);
    rt.artistCount.addAndGet(1);
    rt.playtime.addAndGet(3);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // /folders/add "/src/test/resources/data2/"
    f = new File("src/test/resources/data2/");
    rt.songCount.addAndGet(6);
    rt.playtime.addAndGet(6);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    arr = obj.getJSONArray("folders");
    assertEquals(3, arr.length());
    for (int i = 0; i < 3; i++) {
        String s = new File(arr.getString(i)).getAbsolutePath();
        String s1 = new File("src/test/resources/data").getAbsolutePath();
        String s2 = new File("src/test/resources/data2/sub1").getAbsolutePath();
        String s3 = new File("src/test/resources/data2").getAbsolutePath();
        assertTrue(s.equals(s1) || s.equals(s2) || s.equals(s3));
    }

    // /folders/remove as user: 401
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/remove unknown dir: 400
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/remove "/src/test/resources/data","src/test/resources/data2"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data");
    post.addParameter("directory[]", f.getAbsolutePath());
    f = new File("src/test/resources/data2");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(3);
    rt.albumCount.set(1);
    rt.artistCount.set(1);
    rt.userCount.set(2);
    rt.playtime.set(3);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders/remove "/src/test/resources/data/sub1"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data2/sub1");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(0);
    rt.albumCount.set(0);
    rt.artistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(0);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

}

From source file:gov.va.vinci.leo.tools.JamServiceTest.java

@Test
public void doHttpCallTest() throws IOException {
    HttpClientMock mockHttpClient = new HttpClientMock(200, "test");
    JamService jamService = new JamService("http://localhost/jam");
    jamService.setClient(mockHttpClient);
    String result = jamService.doHttpCall(new GetMethod(
            jamService.getJamServerBaseUrl() + "webservice/removeServiceQueue/" + URLEncoder.encode("mydata")));
    assertTrue(result.equals("test"));
}

From source file:com.owncloud.android.lib.resources.files.SearchOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    GetMethod get = null;/*from w  w w  .j ava 2  s. co m*/

    try {
        get = new GetMethod(client.getBaseUri() + URI);
        get.setQueryString(new NameValuePair[] { new NameValuePair("query", itsQuery) });
        int status = client.executeMethod(get);
        if (checkSuccess(status, get)) {
            Log_OC.d(TAG, "Successful response len: " + get.getResponseContentLength());

            result = new RemoteOperationResult(true, status, get.getResponseHeaders());
            ArrayList<Object> data = new ArrayList<Object>();

            JSONArray respJson = new JSONArray(get.getResponseBodyAsString());
            for (int i = 0; i < respJson.length(); ++i) {
                JSONObject item = respJson.getJSONObject(i);
                data.add(new Result(item.optString("type", null), item.optString("path", null)));
            }

            result.setData(data);
        } else {
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception during search", e);
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

    return result;
}

From source file:eu.delving.services.controller.SolrProxyController.java

@RequestMapping("/api/solr/select")
public void searchController(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final String solrQueryString = request.getQueryString();
    HttpMethod method = new GetMethod(
            String.format("%s/select?%s", ThemeFilter.getTheme().getSolrSelectUrl(), solrQueryString));
    httpClient.executeMethod(method);// www .ja  v a  2 s  .c o  m
    Boolean getAsStream = false;
    for (Header header : method.getResponseHeaders()) {
        if (header.getName().equalsIgnoreCase("content-type")) {
            final String contentType = method.getResponseHeader("Content-Type").getValue();
            response.setContentType(contentType);
            response.setHeader(header.getName(), header.getValue());
            if (contentType.equalsIgnoreCase("application/octet-stream")) {
                getAsStream = true;
            }
        } else if (header.getName().equalsIgnoreCase("server")) {
            //ignore
        } else {
            response.setHeader(header.getName(), header.getValue());
        }
    }
    response.setCharacterEncoding("UTF-8");
    if (getAsStream) {
        OutputStream out = response.getOutputStream();
        try {
            IOUtils.copy(method.getResponseBodyAsStream(), out);
        } finally {
            out.close();
        }
    } else {
        response.getWriter().write(method.getResponseBodyAsString()); //todo add response from SolrProxy here
        response.getWriter().close();
    }
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * Given host, port and schema name, send a http GET request to download the {@link Schema}.
 *
 * @return schema on success./*from  w  w  w. j  a v a 2s  .  c om*/
 * <P><code>null</code> on failure.
 */
public static @Nullable Schema getSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schemaName);

    try {
        URL url = new URL("http", host, port, "/schemas/" + schemaName);
        GetMethod httpGet = new GetMethod(url.toString());
        try {
            int responseCode = HTTP_CLIENT.executeMethod(httpGet);
            String response = httpGet.getResponseBodyAsString();
            if (responseCode >= 400) {
                // File not find error code.
                if (responseCode == 404) {
                    LOGGER.info("Cannot find schema: {} from host: {}, port: {}", schemaName, host, port);
                } else {
                    LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                }
                return null;
            }
            return Schema.fromString(response);
        } finally {
            httpGet.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host,
                port, e);
        return null;
    }
}

From source file:com.ifeng.vdn.ip.repository.service.impl.IPAddressBaiduChecker.java

@Override
public IPAddress ipcheck(String ip) {

    IPAddress ipaddress = null;//from  ww  w .j av  a2 s . c  o  m
    String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + ip
            + "&co=&resource_id=6006&t=1428632527853&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204891062709502876_1428631554303&_=1428631554305";

    // Create an instance of HttpClient.
    HttpClient clinet = new HttpClient();

    // Create a method instance.
    GetMethod getMethod = new GetMethod(url);

    try {
        // Execute the method.
        int statusCode = clinet.executeMethod(getMethod);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failedd: {}", getMethod.getStatusCode());
        } else {
            // Read the response body.
            byte[] responseBody = getMethod.getResponseBody();
            String responseStr = new String(responseBody, "GBK");

            responseStr = responseStr.substring(responseStr.indexOf("(") + 1, responseStr.indexOf(")"));

            ObjectMapper mapper = new ObjectMapper();

            ipaddress = mapper.readValue(responseStr, BaiduIPBean.class);

        }

    } catch (JsonParseException | JsonMappingException | HttpException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return ipaddress;
}