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:att.jaxrs.server.TagService.java

@GET
@Path("/tags/{name}/")
public Response getTag(@PathParam("name") Long name) {
    System.out.println("----invoking getTag, tag id is: " + name);

    GetMethod get = new GetMethod(Constants.SELECT_WITH_NAME_TAG_RESOURCE + name);

    TagCollection tag = new TagCollection();
    try {//  w  w  w.java2s  . c o m

        HttpClient httpClient = new HttpClient();
        try {
            int result = httpClient.executeMethod(get);
            System.out.println(Constants.RESPONSE_STATUS_CODE + result);
            tag = Marshal.unmarshal(TagCollection.class, get.getResponseBodyAsStream());

        } finally {
            get.releaseConnection();
        }
    } catch (Exception e) {

    }
    return Response.ok(tag).build();
}

From source file:eu.eco2clouds.accounting.testbedclient.ClientHC.java

/**
 * Connects to an testbed URL to get the XML representations of Host Info
 * And it returns it as a null/*from   w  w w. j a  v  a 2  s. c  o m*/
 * @param testbed object representing the testbed from which we want to know the host info
 * @return A XML string with the Host info, if there was any HTTP error, it returns empty String... 
 */
public String getHostInfo(Testbed testbed) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(testbed.getUrl());

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

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

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbed: " + testbed.getName() + " failed: "
                    + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:net.jadler.JadlerDeprecatedDefaultsConfigurationTest.java

@Test
@SuppressWarnings("deprecation")
public void ongoingConfiguration() throws IOException {
    initJadler().that().respondsWithDefaultStatus(EXPECTED_STATUS)
            .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE)
            .respondsWithDefaultEncoding(EXPECTED_ENCODING)
            .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE);

    try {/*  w  w  w .j av a  2s.c  om*/
        onRequest().respond().withBody(STRING_WITH_DIACRITICS);

        final HttpClient client = new HttpClient();
        final GetMethod method = new GetMethod("http://localhost:" + port() + "/");
        client.executeMethod(method);

        assertThat(method.getStatusCode(), is(EXPECTED_STATUS));
        assertThat(method.getResponseHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE));
        assertThat(method.getResponseHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE));
        assertThat(method.getResponseBody(), is(ISO_8859_2_REPRESENTATION));

        method.releaseConnection();
    } finally {
        closeJadler();
    }
}

From source file:com.epam.wilma.gepard.test.messagemarker.MessageMarkingSwitch.java

/**
 * Set message marking to on/off.//from ww w  .j  ava  2  s  .  com
 *
 * @param tc is the caller Test Case
 * @param host Wilma host:port string
 * @param state is the expected state of the switch
 * @return with response code
 * @throws Exception in case of error
 */
public String setMessageMarkingModeTo(final WilmaTestLogDecorator tc, final String host, final String state)
        throws Exception {
    String url = String.format(URL_TEMPLATE, host, state);
    tc.logStep("Switching message marking in Wilma to: " + url.split("messagemarking/")[1]);
    tc.logGetRequestEvent(url);

    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod(url);
    int statusCode = httpClient.executeMethod(httpGet);
    String responseCode = "status code: " + statusCode + "\n";
    if (statusCode != STATUS_OK) {
        tc.naTestCase("Message marking switch failed.");
    }
    tc.logComment("Message marking is: " + url.split("messagemarking/")[1]);
    return responseCode;
}

From source file:com.djimenez.tuenti.example.FormLoginDemo.java

/**
 * @param client//from ww w.ja  v a  2  s  . c o  m
 * @param header
 * @throws IOException
 * @throws HttpException
 */
private static void checkHeader(final HttpClient client, final Header header) throws IOException {

    if (header != null) {
        String newuri = header.getValue();
        if ((newuri == null) || (newuri.equals(""))) {
            newuri = "/";
        }
        System.out.println("Redirect target: " + newuri);
        final GetMethod redirect = new GetMethod(newuri);

        client.executeMethod(redirect);
        System.out.println("Redirect: " + redirect.getStatusLine().toString());
        // release any connection resources used by the method
        redirect.releaseConnection();
    } else {
        System.out.println("Invalid redirect");
        System.exit(1);
    }
}

From source file:com.epam.wilma.gepard.test.localhost.BlockLocalhostUsageSwitch.java

/**
 * Set localhost blocking to on/off.//from  w  ww .j a v a 2  s. com
 *
 * @param tc is the caller Test Case
 * @param host Wilma host:port string
 * @param state is the expected state of the switch
 * @return with response code
 * @throws Exception in case of error
 */
public String setLocalhostBlockingModeTo(final WilmaTestLogDecorator tc, final String host, final String state)
        throws Exception {
    String url = String.format(URL_TEMPLATE, host, state);
    tc.logStep("Switching localhost blocking in Wilma to: " + url.split("localhost/")[1]);
    tc.logGetRequestEvent(url);

    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod(url);
    int statusCode = httpClient.executeMethod(httpGet);
    String responseCode = "status code: " + statusCode + "\n";
    if (statusCode != STATUS_OK) {
        tc.naTestCase("Localhost blocking switch failed.");
    }
    tc.logComment("Localhost blocking is: " + url.split("localhost/")[1]);
    return responseCode;
}

From source file:cn.newtouch.util.HttpClientUtil.java

/**
 * ?url??get/*w  ww  .ja v a2 s  . co m*/
 * 
 * @param url
 */
public static String reqUrl(String url) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    try {
        int returnCode = client.executeMethod(method);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
        } else {
            return method.getResponseBodyAsString();

        }
    } catch (Exception e) {
        System.err.println(e);
    }
    return null;
}

From source file:com.manning.blogapps.chapter10.metaweblogclient.MetaWeblogResource.java

public InputStream getAsStream() throws BlogClientException {
    HttpClient httpClient = new HttpClient();
    GetMethod method = new GetMethod(url);
    try {//from   w  w w.ja v  a2  s.  c o m
        httpClient.executeMethod(method);
    } catch (Exception e) {
        throw new BlogClientException("ERROR: error reading file");
    }
    if (method.getStatusCode() != 200) {
        throw new BlogClientException("ERROR HTTP status=" + method.getStatusCode());
    }
    try {
        return method.getResponseBodyAsStream();
    } catch (Exception e) {
        throw new BlogClientException("ERROR: error reading file");
    }
}

From source file:com.epam.wilma.gepard.test.altermessage.ResponseMessageVolatilitySwitch.java

/**
 * Set response message volatility to on/off.
 *
 * @param tc is the caller Test Case//  w  w  w .  j  ava  2  s.co  m
 * @param host Wilma host:port string
 * @param state is the expected state of the switch
 * @return with response code
 * @throws Exception in case of error
 */
public String setResponseMessageVolatilityTo(final WilmaTestLogDecorator tc, final String host,
        final String state) throws Exception {
    String url = String.format(URL_TEMPLATE, host, state);
    tc.logStep("Switching response message volatility in Wilma to: " + url.split("responsevolatility/")[1]);
    tc.logGetRequestEvent(url);

    HttpClient httpClient = new HttpClient();
    GetMethod httpGet = new GetMethod(url);
    int statusCode = httpClient.executeMethod(httpGet);
    String responseCode = "status code: " + statusCode + "\n";
    if (statusCode != STATUS_OK) {
        tc.naTestCase("Response message volatility switch failed.");
    }
    tc.logComment("Response message volatility is: " + url.split("responsevolatility/")[1]);
    return responseCode;
}

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

@Test
public void test() throws IOException, JSONException {
    HttpClient client = new HttpClient();

    // check the users and sessions created by TServer
    GetMethod get = new GetMethod(TServer.URL + "users");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);//from w  w w  . j  av a 2  s . c o m
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    JSONArray users = obj.getJSONArray("users");
    Assert.assertEquals(2, users.length());
    for (int i = 0; i < 2; i++) {
        JSONObject u = users.getJSONObject(i);
        String username = u.getString("username");
        if (username.equals(this.user_username)) {
            Assert.assertEquals(this.user_userId, u.getInt("id"));
            Assert.assertEquals(2, u.getInt("auth"));
            Assert.assertEquals(0, u.getInt("downloaded"));
        } else if (username.equals(this.admin_username)) {
            Assert.assertEquals(this.admin_userId, u.getInt("id"));
            Assert.assertEquals(1, u.getInt("auth"));
            Assert.assertEquals(0, u.getInt("downloaded"));
        } else {
            Assert.fail("Unexpected user:" + username);
        }
    }

    JSONArray sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(2, sessions.length());
    for (int i = 0; i < 2; i++) {
        JSONObject s = sessions.getJSONObject(i);
        String username = s.getString("username");
        if (username.equals(this.user_username)) {
            Assert.assertEquals(this.user_userId, s.getInt("user_id"));
            Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
            Assert.assertTrue(s.getInt("created_at") >= 0);
            Assert.assertFalse(s.has("origins")); // admin only
            Assert.assertFalse(s.has("last_played_song"));
        }
    }

    // unknown user: 404
    get = new GetMethod(TServer.URL + "user/100");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(404, get.getStatusCode());

    // check admin user
    get = new GetMethod(TServer.URL + "user/" + this.admin_userId);
    get.addRequestHeader("sessionId", this.admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    JSONObject u = obj.getJSONObject("user");
    Assert.assertEquals(this.admin_userId, u.getInt("id"));
    Assert.assertEquals(this.admin_username, u.getString("username"));
    Assert.assertEquals(1, u.getInt("auth"));
    Assert.assertEquals(0, u.getInt("downloaded"));
    sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(1, sessions.length());
    JSONObject s = sessions.getJSONObject(0);

    Assert.assertEquals(this.admin_userId, s.getInt("user_id"));
    Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
    Assert.assertTrue(s.getInt("created_at") > 0);
    Assert.assertTrue(s.has("origins")); // admin only
    Assert.assertFalse(s.has("last_played_song"));
    Assert.assertTrue(obj.getJSONArray("playlists").length() == 0);

    // create a new user with user account: error 401
    PostMethod post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.user_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "new-pw");
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // create new user with empty username: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "");
    post.addParameter("password", "new-pw");
    post.addParameter("auth", "1");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // create new user with short password: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "pw");
    post.addParameter("auth", "1");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // create new user with invalid auth: err 400
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", "new-user");
    post.addParameter("password", "pw");
    post.addParameter("auth", "3");
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    int new_userId = -1;
    String new_sessionId = null;
    String new_username = "new-user";
    String new_password = "new-pw";

    // create new user
    post = new PostMethod(TServer.URL + "user/add");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    post.addParameter("username", new_username);
    post.addParameter("password", new_password);
    post.addParameter("auth", "2");
    client.executeMethod(post);
    Assert.assertEquals(200, post.getStatusCode());
    u = new JSONObject(post.getResponseBodyAsString()).getJSONObject("user");
    new_userId = u.getInt("id");
    Assert.assertEquals(new_username, u.getString("username"));
    Assert.assertEquals(2, u.getInt("auth"));

    // check new user 
    get = new GetMethod(TServer.URL + "user/" + new_userId);
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    Assert.assertTrue(obj.getJSONArray("playlists").length() == 0);
    Assert.assertEquals(0, obj.getJSONArray("sessions").length());

    // login new user
    obj = new JSONObject(this.login(new_username, new_password));
    Assert.assertEquals(new_userId, obj.getInt("userId"));
    new_sessionId = obj.getString("sessionId");

    // check if logged in with /users
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", new_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    users = obj.getJSONArray("users");
    Assert.assertEquals(3, users.length());
    for (int i = 0; i < 3; i++) {
        u = users.getJSONObject(i);
        String username = u.getString("username");
        if (username.equals(new_username)) {
            Assert.assertEquals(new_userId, u.getInt("id"));
        } else {
            Assert.assertTrue(username.equals(user_username) || username.equals(admin_username));
        }
    }
    sessions = obj.getJSONArray("sessions");
    Assert.assertEquals(3, sessions.length());
    for (int i = 0; i < 3; i++) {
        s = sessions.getJSONObject(i);
        String username = s.getString("username");
        if (username.equals(new_username)) {
            Assert.assertEquals(new_userId, s.getInt("user_id"));
            Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0
            Assert.assertTrue(s.getInt("created_at") > 0);
            Assert.assertFalse(s.has("origins")); // admin only
            Assert.assertFalse(s.has("last_played_song"));
        } else {
            Assert.assertTrue(username.equals(user_username) || username.equals(admin_username));
        }
    }

    // try to change password without the old password: 401
    post = new PostMethod(URL + "user/password");
    post.addRequestHeader("sessionId", new_sessionId);
    post.addParameter("old_password", "password");
    post.addParameter("new_password", "password2");
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // change password for new user
    post = new PostMethod(URL + "user/password");
    post.addRequestHeader("sessionId", new_sessionId);
    post.addParameter("old_password", new_password);
    new_password = "something else";
    post.addParameter("new_password", new_password);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // logout and relogin with new password
    post = new PostMethod(URL + "logout");
    post.addRequestHeader("sessionId", new_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    obj = new JSONObject(this.login(new_username, new_password));
    Assert.assertEquals(new_userId, obj.getInt("userId"));
    new_sessionId = obj.getString("sessionId");

    // try to delete an user as user: 401
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("user_ids[]", "" + new_userId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // try to delete no user: 400
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // try to delete admin with admin: 400
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("user_ids[]", "" + admin_userId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // delete both regular users
    post = new PostMethod(URL + "user/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("user_ids[]", "" + user_userId);
    post.addParameter("user_ids[]", "" + new_userId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // check that old sessions do not work anymore
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // check that there is only 1 user
    get = new GetMethod(URL + "users");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    Assert.assertEquals(obj.getJSONArray("users").length(), 1);
    Assert.assertEquals(obj.getJSONArray("sessions").length(), 1);

}