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

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

Introduction

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

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:es.carebear.rightmanagement.client.user.ChangeAttributeUser.java

public void ChangeAttribute(String userName, String authName, String[] attribute, String[] value)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    Gson gson = new Gson();
    String attr = gson.toJson(attribute, attribute.getClass());
    String val = gson.toJson(value, value.getClass());

    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/" + userName);
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("attribute", attr);
    postMethod.addParameter("value", val);

    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;/* w  w w.java  2 s . com*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:net.sourceforge.jwbf.actions.mw.old.PostDelete.java

/**
 * //from w  w w.j  ava  2  s.  c  o m
 * @param label of the article
 * @param tab with contains environment variable "wpEditToken"
 * @deprecated
 */
public PostDelete(final String label, Hashtable<String, String> tab) {

    NameValuePair action = new NameValuePair("wpConfirmB", "Delete Page");
    // this value is preseted
    NameValuePair wpReason = new NameValuePair("wpReason", "hier der Grund");
    wpReason.setName("backdraft");

    NameValuePair wpEditToken = new NameValuePair("wpEditToken", tab.get("wpEditToken"));

    PostMethod pm = new PostMethod("/index.php?title=" + label + "&action=delete");

    pm.setRequestBody(new NameValuePair[] { action, wpReason, wpEditToken });
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);
    msgs.add(pm);

}

From source file:de.mpg.imeji.presentation.util.LoginHelper.java

/**
 * Get handle of System administrator of eSciDoc instance.
 * /*from  ww  w. j  av  a  2s  .  c  o  m*/
 * @return
 */
//    public static String loginSystemAdmin()
//    {
//        String handle = null;
//        try
//        {
//            handle = login(PropertyReader.getProperty("framework.admin.username"),
//                    PropertyReader.getProperty("framework.admin.password"));
//        }
//        catch (Exception e)
//        {
//            sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class);
//            BeanHelper
//                    .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e);
//            logger.error("Error escidoc admin login", e);
//        }
//        return handle;
//    }

public static String login(String userName, String password) throws Exception {
    String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url");
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");
    String host = hostPort.nextToken();
    int port = 80;
    if (hostPort.hasMoreTokens()) {
        port = Integer.parseInt(hostPort.nextToken());
    }
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().closeIdleConnections(1000);
    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userName);
    login.addParameter("j_password", password);
    try {
        client.executeMethod(login);
    } catch (Exception e) {
        throw new RuntimeException("Error login in " + frameworkUrl + "  status: " + login.getStatusCode()
                + " - " + login.getStatusText());
    }
    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());
    Cookie sessionCookie = logoncookies[0];
    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + postMethod.getStatusCode());
    }
    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:com.krawler.esp.utils.HttpPost.java

public String invoke(String soapMessage) {
    try {//  w  w w.  java  2 s  . c o m
        int statusCode = -1;
        String mUri = "http://localhost:7070/service/soap/";
        // the content-type charset will determine encoding used
        // when we set the request body
        PostMethod method = new PostMethod(mUri);
        // method.setRequestHeader("Content-type",
        // getSoapProtocol().getContentType());
        method.setRequestBody(soapMessage);
        method.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_AUTO);

        // if (getSoapProtocol().hasSOAPActionHeader())
        // method.setRequestHeader("SOAPAction", mUri);

        // execute the method.
        HttpClient mClient = new HttpClient();
        statusCode = mClient.executeMethod(method);

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Release the connection.
        method.releaseConnection();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data

        String responseStr = toString(responseBody);
        return responseStr;
    } catch (IOException ex) {
        return ex.toString();
    } catch (Exception ex) {
        return ex.toString();
    }
}

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

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

    // good username, bad password: error 401
    PostMethod post = new PostMethod(TServer.URL + "login");
    post.addParameter("username", admin_username);
    post.addParameter("password", "bad_password");
    client.executeMethod(post);/*from   ww  w  .  j av a 2 s  .  c om*/
    post.getResponseBodyAsString();
    Assert.assertEquals(401, post.getStatusCode());

    // empty password and username: error 401
    post = new PostMethod(TServer.URL + "login");
    post.addParameter("username", "");
    post.addParameter("password", "");
    client.executeMethod(post);
    post.getResponseBodyAsString();
    Assert.assertEquals(401, post.getStatusCode());

    // log in as admin
    post = new PostMethod(TServer.URL + "login");
    post.addParameter("username", admin_username);
    post.addParameter("password", admin_password);
    client.executeMethod(post);

    String ret = post.getResponseBodyAsString();
    JSONObject obj = new JSONObject(ret);
    int uid_admin = obj.getInt("userId");
    String sid_admin = obj.getString("sessionId");
    int auth = obj.getInt("auth");

    Assert.assertEquals(200, post.getStatusCode());
    Assert.assertEquals(uid_admin, this.admin_userId);
    Assert.assertNotNull(UUID.fromString(sid_admin));
    Assert.assertEquals(auth, 1);

    // call 'stats' with this session, should succeed
    GetMethod get = new GetMethod(TServer.URL + "stats");
    get.addRequestHeader("sessionId", sid_admin);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());

    // the previous session that was setup by the test case 
    // for this user should NOT have been destroyed
    // both sessions are kept for the same user
    get = new GetMethod(TServer.URL + "stats");
    get.addRequestHeader("sessionId", this.admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());

    // the other user set up by the test case should still be logged in
    get = new GetMethod(TServer.URL + "stats");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());

    // logout all users
    post = new PostMethod(TServer.URL + "logout");
    post.addRequestHeader("sessionId", sid_admin);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    post = new PostMethod(TServer.URL + "logout");
    post.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    post = new PostMethod(TServer.URL + "logout");
    post.addRequestHeader("sessionId", this.admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // check that neither client can call 'stats'
    get = new GetMethod(TServer.URL + "stats");
    get.addRequestHeader("sessionId", sid_admin);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    get = new GetMethod(TServer.URL + "stats");
    get.addRequestHeader("sessionId", this.user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());
}

From source file:ca.uvic.cs.tagsea.wizards.TagNetworkSender.java

public static synchronized void send(String xml, IProgressMonitor sendMonitor, int id)
        throws InvocationTargetException {
    sendMonitor.beginTask("Uploading Tags", 100);
    sendMonitor.subTask("Saving Temporary file...");
    File location = TagSEAPlugin.getDefault().getStateLocation().toFile();
    File temp = new File(location, "tagsea.temp.file.txt");
    if (temp.exists()) {
        String message = "Unable to send tags. Unable to create temporary file.";
        IOException ex = new IOException(message);
        throw (new InvocationTargetException(ex, message));
    }//w  w w .jav a2 s.c o m
    try {
        FileWriter writer = new FileWriter(temp);
        writer.write(xml);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    sendMonitor.worked(5);
    sendMonitor.subTask("Uploading Tags...");
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    PostMethod post = new PostMethod(uploadScript);

    String fileName = getToday() + ".txt";
    try {
        Part[] parts = { new StringPart("KIND", "tag"), new FilePart("MYLAR" + id, fileName, temp) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            IOException ex = new IOException(resp);
            throw (ex);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e, e.getLocalizedMessage());
    } finally {
        sendMonitor.worked(90);
        sendMonitor.subTask("Deleting Temporary File");
        temp.delete();
        sendMonitor.done();
    }

}

From source file:com.autofrog.pandabot.client.PandoraBot.java

public PandorabotResult ask(String custId, String what) throws Exception {
    PostMethod post = new PostMethod(botAddr);
    post.addParameter("botid", botId);
    post.addParameter("custid", custId);
    post.addParameter("input", what);

    int rc = client.executeMethod(post);

    System.out.println(post.getResponseBodyAsString());

    PandorabotResult result = (PandorabotResult) u.unmarshal(post.getResponseBodyAsStream());

    return result;
}

From source file:edu.unc.lib.dl.ui.util.FileIOUtil.java

public static String postImport(HttpServletRequest request, String url) {
    Map<String, String[]> parameters = request.getParameterMap();
    HttpClientParams params = new HttpClientParams();
    params.setContentCharset("UTF-8");
    HttpClient client = new HttpClient();
    client.setParams(params);/* w ww  .  j  a v  a 2  s .  c  o  m*/

    PostMethod post = new PostMethod(url);
    Iterator<Entry<String, String[]>> parameterIt = parameters.entrySet().iterator();
    while (parameterIt.hasNext()) {
        Entry<String, String[]> parameter = parameterIt.next();
        for (String parameterValue : parameter.getValue()) {
            post.addParameter(parameter.getKey(), parameterValue);
        }
    }

    try {
        client.executeMethod(post);
        return post.getResponseBodyAsString();
    } catch (Exception e) {
        throw new ResourceNotFoundException("Failed to retrieve POST import request for " + url, e);
    } finally {
        post.releaseConnection();
    }
}

From source file:net.duckling.ddl.service.version.impl.VersionService.java

@Override
public Version get(String project, String type) {
    HttpClient dClient = new HttpClient();
    PostMethod method = new PostMethod(getDupdateUrl());
    method.setParameter("type", type);
    method.setParameter("project", project);
    try {/* w  w  w . j  a v  a  2  s  .co  m*/
        dClient.executeMethod(method);
        String response = method.getResponseBodyAsString();
        Map<String, String> map = parseResponse(response);

        Version v = new Version();
        if (map.get("success").equals("true")) {
            v.setVersion(map.get("version"));
            v.setDownloadUrl(map.get("downloadUrl"));
            v.setForcedUpdate(Boolean.valueOf(map.get("forcedUpdate")));
            v.setDescription(map.get("description"));
            v.setCreateTime(map.get("createTime"));
        }
        v.setSuccess(Boolean.valueOf(map.get("success")));
        return v;
    } catch (HttpException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (ParseException e) {
        LOG.error("", e);
    }
    return null;
}

From source file:com.bbva.arq.devops.ae.mirrorgate.jenkins.plugin.utils.RestCall.java

public MirrorGateResponse makeRestCallPost(String url, String jsonString, String user, String password) {

    MirrorGateResponse response;/* w  w w .java 2  s  .  c  om*/
    PostMethod post = new PostMethod(url);
    try {
        HttpClient client = getHttpClient();

        if (user != null && password != null) {
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            post.setDoAuthentication(true);
        }

        StringRequestEntity requestEntity = new StringRequestEntity(jsonString, "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        int responseCode = client.executeMethod(post);
        String responseString = post.getResponseBodyAsStream() != null
                ? getResponseString(post.getResponseBodyAsStream())
                : "";
        response = new MirrorGateResponse(responseCode, responseString);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "MirrorGate: Error posting to MirrorGate", e);
        response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
    } finally {
        post.releaseConnection();
    }
    return response;
}