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:com.amazon.dtasdk.v2.connection.SignatureVerificationTest.java

@Test
public void roundTrip_NoAuth() throws Exception {
    Credential credential = new Credential("SECRETKEY", "KEYID");
    handler.setCredential(credential);//  w w w  . ja v a2s .  c o m

    PostMethod method = new PostMethod(serverUrl() + "/path/to/servlet");
    method.setRequestBody("{\"json\": \"value\"}");

    assertEquals(403, client.executeMethod(method));
}

From source file:au.org.ala.cas.client.WebServiceAuthenticationHelper.java

/**
 * Obtains a Service ticket for a web service invocation.
 * //from  ww  w  . j  av  a  2 s .c o m
 * @param server CAS server URI
 * @param ticketGrantingTicket TGT id
 * @param service Web service URI
 * @return Service ticket id
 */
private String getServiceTicket(final String server, final String ticketGrantingTicket, final String service) {
    if (ticketGrantingTicket == null)
        return null;

    final HttpClient client = new HttpClient();

    final PostMethod post = new PostMethod(server + CAS_CONTEXT + ticketGrantingTicket);

    post.setRequestBody(new NameValuePair[] { new NameValuePair("service", service) });

    try {
        client.executeMethod(post);

        final String response = post.getResponseBodyAsString();

        switch (post.getStatusCode()) {
        case 200:
            return response;

        default:
            logger.warn("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }
    }

    catch (final IOException e) {
        logger.warn(e.getMessage(), e);
    }

    finally {
        post.releaseConnection();
    }

    return null;
}

From source file:hk.hku.cecid.corvus.http.HttpSenderUnitTest.java

/** Test whether the HTTP sender able to send the HTTP header with multi-part to our monitor successfully. */
public void testSendWithMultipart() throws Exception {
    this.target = new HttpSender(this.testClassLogger, new KVPairData(0)) {

        public HttpMethod onCreateRequest() throws Exception {
            PostMethod method = new PostMethod("http://localhost:1999");
            Part[] parts = { new StringPart("testparamName", "testparamValue") };
            method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
            return method;
        }/*from   w ww  .  ja  v  a  2s .  c  o m*/
    };
    this.assertSend();
}

From source file:dept_integration.Dept_Integchalan.java

public static String doSend(String STATUS, String TRANS_DATE, String TRANSID, String BANK_REFNO,
        String BANK_NAME, String CIN) throws Exception {
    String SCODE = "ihSkaRaA";
    String url = "http://wsdl.jhpolice.gov.in/smsresponse.php";
    String result = null;//from   www .java2  s  .c o m
    HttpClient client = null;
    PostMethod method = null;
    client = new HttpClient(new MultiThreadedHttpConnectionManager());

    method = new PostMethod(url);
    // method.addRequestHeader("Content-Type","application/xml");

    method.addParameter("STATUS", STATUS);
    // method.addParameter("signature",URLEncoder.encode(b,"UTF-8"));
    method.addParameter("TRANS_DATE", TRANS_DATE);
    method.addParameter("TRANSID", TRANSID);
    method.addParameter("BANK_REFNO", BANK_REFNO);
    method.addParameter("BANK_NAME", BANK_NAME);
    method.addParameter("CIN", CIN);
    method.addParameter("SCODE", SCODE);

    try {
        int statusCode = client.executeMethod(method);
        // System.out.println("lll"+method.getStatusLine().toString());
        if (statusCode == -1) {
            result = "N";
            System.err.println("HttpError: " + method.getStatusLine());
        } else {
            result = method.getResponseBodyAsString();
            System.out.println(result);
            //result= result.indexOf(""+mobile_no)==-1 ? "N" : "Y";
        }
    } catch (Exception e) {

        e.printStackTrace();

        System.err.println("Fatal protocol violation: " + e.getMessage());
        throw e;

    }

    finally {
        method.abort();
        method.releaseConnection();

    }

    return result;
}

From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.ImageStoreServiceImpl.java

public String requestJSON(String sessionId, Method method, String uri, Parameter[] params) {

    UserInfoWeb user;/*ww  w  . java2s .c  om*/
    try {
        user = EucalyptusWebBackendImpl.getUserRecord(sessionId);
    } catch (Exception e) {
        return errorJSON("Session authentication error: " + e.getMessage());
    }

    NameValuePair[] finalParams;
    try {
        finalParams = getFinalParameters(method, uri, params, user);
    } catch (MalformedURLException e) {
        return errorJSON("Malformed URL: " + uri);
    }

    HttpClient client = new HttpClient();

    HttpMethod httpMethod;
    if (method == Method.GET) {
        GetMethod getMethod = new GetMethod(uri);
        httpMethod = getMethod;
        getMethod.setQueryString(finalParams);
    } else if (method == Method.POST) {
        PostMethod postMethod = new PostMethod(uri);
        httpMethod = postMethod;
        postMethod.addParameters(finalParams);
    } else {
        throw new UnsupportedOperationException("Unknown method");
    }

    try {
        int statusCode = client.executeMethod(httpMethod);
        String str = "";
        InputStream in = httpMethod.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        return str;
    } catch (HttpException e) {
        return errorJSON("Protocol error: " + e.getMessage());
    } catch (IOException e) {
        return errorJSON("Proxy error: " + e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticate(Long operatorId, String username, String password) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE);
    AuthenticationRequest request = new AuthenticationRequest();
    request.setOperatorId(operatorId);//  w w  w  . ja  v  a2s  .  c om
    request.setUserName(username);
    request.setPassword(password);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.unicauca.braim.http.HttpBraimClient.java

public Session POST_Session(String user_id, String access_token) throws IOException {
    Session session = null;//from w w w  .  jav  a  2s.  c o  m
    Gson gson = new Gson();

    String data = "?session[user_id]=" + user_id;
    String token_data = "&braim_token=" + access_token;

    PostMethod method = new PostMethod(api_url + "/api/v1/sessions");
    method.addParameter("session[user_id]", user_id);
    method.addParameter("braim_token", access_token);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_CREATED) {
        System.err.println("Method failed: " + method.getStatusLine());
        throw new IOException("The session was not being created");
    }

    byte[] responseBody = method.getResponseBody();
    String response = new String(responseBody, "UTF-8");
    session = gson.fromJson(response, Session.class);
    System.out.println("new session of" + session.getUser_id() + "was created");

    return session;
}

From source file:jp.co.cyberagent.jenkins.plugins.AndroidAppZonePublisher.java

@Override
public boolean perform(final AbstractBuild build, final Launcher launcher, final BuildListener listener) {
    StringBuilder changeLog = new StringBuilder();
    for (Object changeObject : build.getChangeSet().getItems()) {
        ChangeLogSet.Entry change = (ChangeLogSet.Entry) changeObject;
        if (changeLog.length() > 0) {
            changeLog.append("\n");
        }// w w  w .j  a v  a  2 s  . co  m
        changeLog.append(change.getMsg() + " (" + change.getAuthor().getDisplayName() + ")");
    }
    String server = getDescriptor().getServer();
    if (server == null || server.length() == 0) {
        listener.getLogger().println(TAG + "AppZone server not set. Please set in global config! Aborting.");
        return false;
    }

    List<FilePath> files = getPossibleAppFiles(build, listener);
    if (files.isEmpty()) {
        listener.getLogger().println(TAG + "No file to publish found. Skip.");
        return true;
    }
    Iterator<FilePath> fileIterator = files.iterator();
    while (fileIterator.hasNext()) {
        try {
            FilePath file = fileIterator.next();
            String fileName = file.getName();
            DeployStrategy deploy;
            listener.getLogger().println(TAG + "File: " + fileName);
            if (fileName.endsWith(".apk")) {
                deploy = new DeployStrategyAndroid(server, id, tag, prependNameToTag, file, build, listener);
            } else if (fileName.endsWith(".ipa")) {
                deploy = new DeployStrategyIOs(server, id, tag, prependNameToTag, file, build, listener);
            } else {
                return false;
            }
            deploy.setApiKey(getDescriptor().getApikey());
            deploy.setChangeLog(changeLog.toString());
            listener.getLogger().println(TAG + "Version: " + deploy.getVersion());
            listener.getLogger().println(TAG + "Publishing to: " + deploy.getUrl());

            setUpSsl();
            HttpClient httpclient = new HttpClient();
            PostMethod filePost = new PostMethod(deploy.getUrl());
            List<Part> parts = deploy.getParts();
            filePost.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams()));
            httpclient.executeMethod(filePost);
            int statusCode = filePost.getStatusCode();
            if (statusCode < 200 || statusCode > 299) {
                String body = filePost.getResponseBodyAsString();
                listener.getLogger().println(TAG + "Response (" + statusCode + "):" + body);
                return false;
            }
        } catch (IOException e) {
            listener.getLogger().print(e.getMessage());
            return false;
        }
    }
    return true;
}

From source file:net.adamcin.granite.client.packman.http3.Http3PackageManagerClient.java

private boolean loginLegacy(String username, String password) throws IOException {
    PostMethod request = new PostMethod(getBaseUrl() + LEGACY_PATH);
    request.addParameter(LEGACY_PARAM_USERID, username);
    request.addParameter(LEGACY_PARAM_PASSWORD, password);
    request.addParameter(LEGACY_PARAM_WORKSPACE, LEGACY_VALUE_WORKSPACE);
    request.addParameter(LEGACY_PARAM_TOKEN, LEGACY_VALUE_TOKEN);
    request.addParameter(LOGIN_PARAM_CHARSET, LOGIN_VALUE_CHARSET);

    return getClient().executeMethod(request) == 200;
}

From source file:com.gm.machine.util.CommonUtils.java

/**
 * /*www  . ja  v a2 s.c  o m*/
 * ????
 * 
 * @since 2013-1-12
 * @author qingang
 * @param url
 *            ?????
 * @param remark
 *            
 * @param path
 *            ??
 * @param encoding
 *            ??
 * @throws Exception
 */
public static void createHtmlPage(String url, String remark, String path, String encoding) throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);

    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "ISO-8859-1"));
            String tmp = null;
            StringBuffer htmlRet = new StringBuffer();
            while ((tmp = reader.readLine()) != null) {
                htmlRet.append(tmp + "\n");
            }
            writeHtml(path,
                    Global.HMTLPAGE_CHARSET + new String(htmlRet.toString().getBytes("ISO-8859-1"), encoding),
                    encoding);
            System.out.println("??=====================??" + remark + "===" + url
                    + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                    + "=======================");
        } 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);
        System.out.println("?=====================??" + remark + "===" + url
                + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                + "=======================");
        e.printStackTrace();
        throw e;
    } finally {
        httpMethod.releaseConnection();
    }

}