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:eu.flatworld.worldexplorer.layer.nltl7.NLTL7HTTPProvider.java

@Override
public void run() {
    while (true) {
        while (getQueueSize() != 0) {
            Tile tile = peekTile();/* www. ja va  2s . c o  m*/
            synchronized (tile) {
                String s = String.format(NLTL7Layer.HTTP_BASE, tile.getL(), tile.getX(), tile.getY());
                LogX.log(Level.FINER, s);
                GetMethod gm = new GetMethod(s);
                gm.setRequestHeader("User-Agent", WorldExplorer.USER_AGENT);
                try {
                    int response = client.executeMethod(gm);
                    LogX.log(Level.FINEST, NAME + " " + response + " " + s);
                    if (response == HttpStatus.SC_OK) {
                        InputStream is = gm.getResponseBodyAsStream();
                        BufferedImage bi = ImageIO.read(is);
                        is.close();
                        if (bi != null) {
                            tile.setImage(bi);
                        }
                    }
                } catch (Exception ex) {
                    LogX.log(Level.FINER, "", ex);
                } finally {
                    gm.releaseConnection();
                }
                LogX.log(Level.FINEST, NAME + " dequeueing: " + tile);
                unqueueTile(tile);
            }
            firePropertyChange(P_DATAREADY, null, tile);
            Thread.yield();
        }
        firePropertyChange(P_IDLE, false, true);
        try {
            Thread.sleep(QUEUE_SLEEP_TIME);
        } catch (Exception ex) {
        }
        ;
    }
}

From source file:it.drwolf.ridire.utility.test.SSLConnectionTest.java

public SSLConnectionTest() {
    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 8443));
    this.httpClient = new HttpClient();
    // this.httpClient.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin");
    this.httpClient.getState().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds);
    PostMethod method = new PostMethod("https://localhost:8443/engine");
    method.addParameter(new NameValuePair("action", "rescan"));
    try {//  w w w .  ja  v a2  s .  c  o  m
        int status = this.httpClient.executeMethod(method);
        Header redirectLocation = method.getResponseHeader("location");
        String loc = redirectLocation.getValue();
        GetMethod getmethod = new GetMethod("https://localhost:8443/engine");
        status = this.httpClient.executeMethod(getmethod);
        System.out.println(status);
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

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

/**
 * @param client Client object/*w  w  w.ja  v a 2 s. co  m*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    GetMethod getMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        getMethod = new GetMethod(client.getBaseUri() + METADATA_URL + fileId + JSON_FORMAT);
        getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        int status = client.executeMethod(getMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            String response = getMethod.getResponseBodyAsString();

            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String metadata = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA)
                    .get(NODE_META_DATA);

            result = new RemoteOperationResult(true, getMethod);
            ArrayList<Object> metadataArray = new ArrayList<>();
            metadataArray.add(metadata);
            result.setData(metadataArray);
        } else {
            result = new RemoteOperationResult(false, getMethod);
            client.exhaustResponse(getMethod.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Fetching of metadata for folder " + fileId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (getMethod != null)
            getMethod.releaseConnection();
    }
    return result;
}

From source file:ch.algotrader.starter.GoogleIntradayDownloader.java

private void retrieve(HttpClient httpclient, String symbol, int interval, int tradingDays)
        throws IOException, HttpException, FileNotFoundException {

    GetMethod fileGet = new GetMethod("http://www.google.com/finance/getprices?" + "q=" + symbol + "&i="
            + interval + "&p=" + tradingDays + "d" + "&f=d,o,h,l,c,v");

    fileGet.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {//  ww  w . j av  a  2 s  .c o m
        int status = httpclient.executeMethod(fileGet);

        if (status == HttpStatus.SC_OK) {

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(fileGet.getResponseBodyAsStream()));

            File parent = new File("files" + File.separator + "google");
            if (!parent.exists()) {
                FileUtils.forceMkdir(parent);
            }

            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(new File(parent, symbol + "-" + (interval / 60) + "min.csv")));

            writer.write("dateTime,open,high,low,close,vol,barSize,security\n");

            try {

                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();

                String line;
                long timestamp = 0;
                while ((line = reader.readLine()) != null) {
                    String tokens[] = line.split(",");

                    long time;
                    String timeStampString = tokens[0];
                    if (timeStampString.startsWith("a")) {
                        timestamp = Long.parseLong(timeStampString.substring(1)) * 1000;
                        time = timestamp;
                    } else {
                        time = timestamp + Integer.parseInt(timeStampString) * interval * 1000;
                    }

                    writer.write(Long.toString(time));
                    writer.write(",");
                    writer.write(tokens[1]);
                    writer.write(",");
                    writer.write(tokens[2]);
                    writer.write(",");
                    writer.write(tokens[3]);
                    writer.write(",");
                    writer.write(tokens[4]);
                    writer.write(",");
                    writer.write(tokens[5]);
                    writer.write(",");
                    writer.write("MIN_" + interval / 60);
                    writer.write(",");
                    writer.write(symbol);
                    writer.write("\n");
                }

            } finally {
                reader.close();
                writer.close();
            }
        }
    } finally {
        fileGet.releaseConnection();
    }
}

From source file:com.thoughtworks.go.helpers.HttpClientHelper.java

private HttpMethod doRequest(String path, RequestMethod methodRequired, String params) throws IOException {
    HttpMethod method = null;//from   w ww. j  ava2 s .  co  m
    String url = baseUrl + path;
    switch (methodRequired) {
    case PUT:
        method = new PutMethod(url);
        break;
    case POST:
        method = new PostMethod(url);
        break;
    case GET:
        method = new GetMethod(url);
        break;
    }
    method.setQueryString(params);
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    return method;
}

From source file:com.alibaba.antx.config.resource.http.HttpResource.java

private void load() {
    if (content != null) {
        return;//from  w w  w .jav  a  2  s .  co m
    }

    GetMethod httpget = new GetMethod(getURI().toString());
    httpget.setDoAuthentication(true);
    InputStream stream = null;

    try {
        ResourceContext.get().setCurrentURI(getURI().getURI());

        ((HttpSession) getSession()).getClient().executeMethod(httpget);

        if (httpget.getStatusCode() != 200) {
            throw new ResourceNotFoundException(HttpStatus.getStatusText(httpget.getStatusCode()));
        }

        // ????????
        ResourceContext.get().getVisitedURIs().remove(new ResourceKey(new ResourceURI(getURI().getURI())));

        content = httpget.getResponseBody();
        charset = httpget.getResponseCharSet();

        Header contentTypeHeader = httpget.getResponseHeader("Content-Type");
        contentType = contentTypeHeader == null ? null : contentTypeHeader.getValue();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new ConfigException(e);
    } finally {
        ResourceContext.get().setCurrentURI(null);

        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }

        httpget.releaseConnection();
    }
}

From source file:demo.jaxrs.client.Client.java

public void getCustomerInfo(String name, String password, int id) throws Exception {

    System.out.println("HTTP GET to query customer info, user : " + name + ", password : " + password);
    GetMethod get = new GetMethod("http://localhost:9002/customerservice/customers/" + id);
    setMethodHeaders(get, name, password);
    handleHttpMethod(get);//from  w w  w. j  ava 2  s .c om
}

From source file:com.bt.aloha.batchtest.v2.RemoteTomcatStackRunner.java

private String getResponse(String uri) {
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(getUsername(), getPassword()));
    HttpMethod getMethod = new GetMethod(uri);
    getMethod.setDoAuthentication(true);

    try {/*from   w  w w.  j  av  a  2s. c  om*/
        int rc = httpClient.executeMethod(getMethod);
        LOG.debug(rc);
        if (rc != 200)
            throw new RuntimeException(String.format("bad http response from Tomcat: %d", rc));
        return getMethod.getResponseBodyAsString();
    } catch (HttpException e) {
        LOG.warn(e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOG.warn(e);
        throw new RuntimeException(e);
    }
}

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

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

    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);//  ww  w .  j ava  2  s  .co  m
    rt.albumCount.set(5);
    rt.artistCount.set(2);
    rt.userCount.set(2);
    rt.playlistCount.set(0);
    rt.playtime.set(15);
    rt.downloaded.set(0);
    // add mp3 folder to server indexer
    this.addMusicFolder("src/test/resources/data", rt);

    // get artists list
    GetMethod get = new GetMethod(URL + "artists");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    JSONArray artists = obj.getJSONArray("artists");
    Assert.assertEquals(2, artists.length());
    for (int i = 0; i < artists.length(); i++) {
        Artist artist = new Artist(artists.getJSONObject(i).getJSONObject("artist").toString());
        JSONArray artworks = artists.getJSONObject(i).getJSONArray("artworks");
        Assert.assertEquals(getArtist(artist.name), artist);

        for (Album album : getAlbums(artist)) {
            assertEquals(getAlbum(album.name), album);

            boolean art = false;
            for (int j = 0; j < artworks.length(); j++) {
                if (artworks.getJSONObject(j).getInt("album") == album.id) {
                    art = true;
                }
            }
            assertEquals(album.has_art, art);

            // check artwork is present
            get = new GetMethod(URL + "art/" + album.id);
            client.executeMethod(get);
            if (art) {
                Assert.assertEquals(200, get.getStatusCode());
                Assert.assertEquals("image/jpeg", get.getResponseHeader("Content-Type").getValue());
            } else {
                Assert.assertEquals(404, get.getStatusCode());
            }

            for (Song song : getSongs(album, artist)) {
                Song ex_song = getSong(song.title);
                assertEquals(ex_song, song);

                get = new GetMethod(URL + "song/" + song.id);
                get.addRequestHeader("sessionId", user_sessionId);
                client.executeMethod(get);
                Assert.assertEquals(200, get.getStatusCode());

                obj = new JSONObject(get.getResponseBodyAsString());
                Song s = new Song(obj.getJSONObject("song").toString());
                Album al = new Album(obj.getJSONObject("album").toString());
                Artist ar = new Artist(obj.getJSONObject("artist").toString());
                Assert.assertEquals(ex_song, s);
                Assert.assertEquals(getArtist(artist.name), ar);
                Assert.assertEquals(getAlbum(album.name), al);

                // check that the stream works
                get = new GetMethod(URL + "song/" + song.id + "/stream?sessionId=" + user_sessionId);
                client.executeMethod(get);
                Assert.assertEquals(200, get.getStatusCode());
                int len = (int) new File(ex_song.filepath).length();
                int len2 = Integer.parseInt(get.getResponseHeader("Content-Length").getValue());
                Assert.assertEquals(len, len2);
                Assert.assertEquals("audio/mpeg", get.getResponseHeader("Content-Type").getValue());
            }
        }
    }

    // search/ should be 404
    get = new GetMethod(URL + "search/");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    // search/foo should return only artist 'Foo'
    get = new GetMethod(URL + "search/foo?sessionId=" + user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("albums").length());
    assertEquals(0, obj.getJSONArray("songs").length());
    artists = obj.getJSONArray("artists");
    assertEquals(1, artists.length());
    assertEquals(getArtist("Foo"), new Artist(artists.get(0).toString()));

    // search/y should return nothing
    get = new GetMethod(URL + "search/y");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("albums").length());
    assertEquals(0, obj.getJSONArray("artists").length());
    assertEquals(0, obj.getJSONArray("songs").length());

    // search/te should return 4 songs: ten,thirteen,fourteen,fifteen
    get = new GetMethod(URL + "search/te");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("albums").length());
    assertEquals(0, obj.getJSONArray("artists").length());
    JSONArray songs = obj.getJSONArray("songs");
    assertEquals(4, songs.length());
    for (int i = 0; i < songs.length(); i++) {
        Song s = new Song(songs.get(i).toString());
        assertTrue(s.title.equals("Ten") || s.title.equals("Thirteen") || s.title.equals("Fourteen")
                || s.title.equals("Fifteen"));
        assertEquals(getSong(s.title), s);
    }

    // search/o shoud return 1 album, 2 artists, 4 songs
    get = new GetMethod(URL + "search/o");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    JSONArray albums = obj.getJSONArray("albums");
    artists = obj.getJSONArray("artists");
    songs = obj.getJSONArray("songs");
    assertEquals(1, albums.length());
    assertEquals(getAlbum("Ok"), new Album(albums.get(0).toString()));
    assertEquals(2, artists.length());
    for (int i = 0; i < artists.length(); i++) {
        Artist a = new Artist(artists.get(i).toString());
        assertTrue(a.name.equals("Bob") || a.name.equals("Foo"));
        assertEquals(getArtist(a.name), a);
    }
    assertEquals(4, songs.length());
    for (int i = 0; i < songs.length(); i++) {
        Song s = new Song(songs.get(i).toString());
        assertTrue(s.title.equals("Fourteen") || s.title.equals("Four") || s.title.equals("Two")
                || s.title.equals("One"));
        assertEquals(getSong(s.title), s);
    }

}

From source file:de.mpg.escidoc.services.validation.xmltransforming.ConeContentHandler.java

@Override
public void processingInstruction(String name, String params) throws SAXException {
    if (!"cone".equals(name)) {
        super.processingInstruction(name, params);
    } else {//  w  ww.  j  av a  2s .c o m
        try {
            String url = PropertyReader.getProperty("escidoc.cone.service.url") + params + "/all?format=rdf";

            logger.info("Trying to retrieve CoNE data from :" + url);

            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            ProxyHelper.executeMethod(client, method);
            if (method.getStatusCode() == 200) {
                InputStream inputStream = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read;
                byte[] buffer = new byte[2048];
                while ((read = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, read);
                }
                String response = new String(baos.toByteArray());
                response = response.replaceAll("<\\?xml[^>]+\\?>", "");
                super.append(response);
            } else {
                logger.warn("CoNE service returned status code " + method.getStatusCode());
                logger.warn("CoNE data not included");
            }
        } catch (Exception e) {
            logger.error("Error getting CoNE data", e);
        }
    }
}