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.liaison.service.resources.examples.HelloWorldResource.java

private String sendPost(String authToken) {

    try {/*from w  w w  . ja va 2s  . c o  m*/

        String JSON_STRING = "{\"oneTimeToken\" : \"{TOKEN}\"}".replace("{TOKEN}", authToken);

        PostMethod postMethod = new PostMethod(POST_URL);
        postMethod.setRequestBody(JSON_STRING);

        // Must send "Content-Type:application/json"
        Header header = new Header("Content-Type", "application/json");

        postMethod.addRequestHeader(header);

        HttpClient httpClient = new HttpClient();

        int statusCode = httpClient.executeMethod(postMethod);

        String response = new String(postMethod.getResponseBody());

        postMethod.releaseConnection();

        return response;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sourceforge.jcctray.model.CCNet.java

protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new PostMethod(forceBuildURL(project));
    configureMethod(method, project);//from   ww w.  j a  v a2  s .  c o m
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java

private Map<String, String> login() throws HttpException, IOException {
    StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT)
            .append(ACHttpPropertiesConstant.HTTP_SESSION_CONTROL_URL);
    postMethod = new PostMethod(sb.toString());

    postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);

    StringRequestEntity requestEntity = new StringRequestEntity(
            ACHttpBodyUtil.buildLoginRequestBody(USER_ID, PASSWORD), null,
            ACHttpPropertiesConstant.HTTP_CHARSET);
    postMethod.setRequestEntity(requestEntity);

    int statusCode = client.executeMethod(postMethod);

    assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

    return ACHttpBodyUtil.buildParameterMap(postMethod.getResponseBodyAsStream(),
            ACHttpPropertiesConstant.HTTP_CHARSET);
}

From source file:com.spun.util.ups.UPSUtils.java

/***********************************************************************/
public static UPSQuote[] getQuote(UPSConfig config, String reqbody) throws SAXException,
        ParserConfigurationException, FactoryConfigurationError, HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(UPS_URL);
    post.setRequestBody(reqbody);/*from w  w  w  .  j ava 2  s  .c  o m*/
    InputStream response = quoteRetriever.getResponse(client, post);
    UPSQuote[] quotes = extractQuotes(response);
    return quotes;
}

From source file:edu.caltech.ipac.firefly.server.util.multipart.MultiPartPostBuilder.java

/**
 * Post this multipart request.// w  w w . ja  v  a  2  s.co m
 * @param responseBody  the response is written into this OutputStream.
 * @return a MultiPartRespnse which contains headers, status, and status code.
 */
public MultiPartRespnse post(OutputStream responseBody) {

    if (targetURL == null || parts.size() == 0) {
        return null;
    }

    logStart();

    PostMethod filePost = new PostMethod(targetURL);

    for (Param p : headers) {
        filePost.addRequestHeader(p.getName(), p.getValue());
    }

    try {

        filePost.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams()));

        HttpServices.executeMethod(filePost, userId, passwd);

        MultiPartRespnse resp = new MultiPartRespnse(filePost.getResponseHeaders(), filePost.getStatusCode(),
                filePost.getStatusText());
        if (responseBody != null) {
            readBody(responseBody, filePost.getResponseBodyAsStream());
        }
        return resp;

    } catch (Exception ex) {
        LOG.error(ex, "Error while posting multipart request to" + targetURL);
        return null;
    } finally {
        filePost.releaseConnection();
    }
}

From source file:edu.unc.lib.dl.admin.controller.IngestController.java

@RequestMapping(value = "ingest/{pid}", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> ingestPackageController(@PathVariable("pid") String pid,
        @RequestParam("type") String type, @RequestParam(value = "name", required = false) String name,
        @RequestParam("file") MultipartFile ingestFile, HttpServletRequest request,
        HttpServletResponse response) {/*from www. j ava 2 s .co  m*/
    String destinationUrl = swordUrl + "collection/" + pid;
    HttpClient client = HttpClientUtil.getAuthenticatedClient(destinationUrl, swordUsername, swordPassword);
    client.getParams().setAuthenticationPreemptive(true);
    PostMethod method = new PostMethod(destinationUrl);

    // Set SWORD related headers for performing ingest
    method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    method.addRequestHeader("Packaging", type);
    method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername());
    method.addRequestHeader("Content-Type", ingestFile.getContentType());
    method.addRequestHeader("Content-Length", Long.toString(ingestFile.getSize()));
    method.addRequestHeader("mail", request.getHeader("mail"));
    method.addRequestHeader("Content-Disposition", "attachment; filename=" + ingestFile.getOriginalFilename());
    if (name != null && name.trim().length() > 0)
        method.addRequestHeader("Slug", name);

    // Setup the json response
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("action", "ingest");
    result.put("destination", pid);
    try {
        method.setRequestEntity(
                new InputStreamRequestEntity(ingestFile.getInputStream(), ingestFile.getSize()));
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Object successfully "create", or at least queued
        if (method.getStatusCode() == 201) {
            Header location = method.getResponseHeader("Location");
            String newPid = location.getValue();
            newPid = newPid.substring(newPid.lastIndexOf('/'));
            result.put("pid", newPid);
        } else if (method.getStatusCode() == 401) {
            // Unauthorized
            result.put("error", "Not authorized to ingest to container " + pid);
        } else if (method.getStatusCode() == 400 || method.getStatusCode() >= 500) {
            // Server error, report it to the client
            result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName()
                    + "\" to " + pid);

            // Inspect the SWORD response, extracting the stacktrace
            InputStream entryPart = method.getResponseBodyAsStream();
            Abdera abdera = new Abdera();
            Parser parser = abdera.getParser();
            Document<Entry> entryDoc = parser.parse(entryPart);
            Object rootEntry = entryDoc.getRoot();
            String stackTrace;
            if (rootEntry instanceof FOMExtensibleElement) {
                stackTrace = ((org.apache.abdera.parser.stax.FOMExtensibleElement) entryDoc.getRoot())
                        .getExtension(SWORD_VERBOSE_DESCRIPTION).getText();
                result.put("errorStack", stackTrace);
            } else {
                stackTrace = ((Entry) rootEntry).getExtension(SWORD_VERBOSE_DESCRIPTION).getText();
                result.put("errorStack", stackTrace);
            }
            log.warn("Failed to upload ingest package file " + ingestFile.getName() + " from user "
                    + GroupsThreadStore.getUsername(), stackTrace);
        }
        return result;
    } catch (Exception e) {
        log.warn("Encountered an unexpected error while ingesting package " + ingestFile.getName()
                + " from user " + GroupsThreadStore.getUsername(), e);
        result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName()
                + "\" to " + pid);
        return result;
    } finally {
        method.releaseConnection();
        try {
            ingestFile.getInputStream().close();
        } catch (IOException e) {
            log.warn("Failed to close ingest package file", e);
        }
    }
}

From source file:com.nokia.helium.diamonds.DiamondsClient.java

private PostMethod getPostMethod(String fileName, String urlPath) {

    // Get the Diamonds XML-file which is to be exported
    File input = new File(fileName);

    // Prepare HTTP post
    PostMethod post = new PostMethod(urlPath);

    // Request content will be retrieved directly
    // from the input stream

    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);//from  ww  w  . j  a v a 2s  .c om
    return post;
}

From source file:com.owncloud.android.CrashlogSendActivity.java

@Override
public void onClick(DialogInterface dialog, final int which) {
    new Thread(new Runnable() {

        @Override//from  ww  w.  j  a va2 s .  co  m
        public void run() {
            // TODO Auto-generated method stub
            File file = new File(mLogFilename);
            if (which == Dialog.BUTTON_POSITIVE) {
                try {
                    HttpClient client = new HttpClient();
                    PostMethod post = new PostMethod(CRASHLOG_SUBMIT_URL);
                    Part[] parts = { new FilePart("crashfile", file) };
                    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
                    client.executeMethod(post);
                    post.releaseConnection();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            file.delete();
            finish();
        }
    }).start();
}

From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java

/**
 * Create a juxta user account. This will throw if create request failed.
 * /*from   w  w w  .  j a  v  a  2 s  . c o  m*/
 * @param email
 * @param pass
 * @param confirm
 * @param confirm2 
 * @throws IOException 
 */
public void createAccount(final String name, final String email, final String pass, final String confirm)
        throws IOException {
    PostMethod post = new PostMethod(this.baseUrl + "/login/create");
    String json = "{\"user\": {" + "\"name\": \"" + name + "\", \"email\": \"" + email + "\", \"password\": \""
            + pass + "\", \"password_confirmation\": \"" + confirm + "\"} }";
    post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
    post.setRequestHeader("accept", "application/json");
    int respCode = execRequest(post, false);
    if (respCode != 200) {
        final String msg = getResponseString(post);
        post.releaseConnection();
        throw new IOException("Unable to create account: " + msg);
    }
    String out = getResponseString(post);
    System.out.println(out);
    post.releaseConnection();
}

From source file:CertStreamCallback.java

private static HttpMethod getHttpMethod(String url, String method) {
    if ("delete".equals(method)) {
        return new DeleteMethod(url);

    } else if ("get".equals(method)) {
        return new GetMethod(url);

    } else if ("post".equals(method)) {
        return new PostMethod(url);

    } else if ("put".equals(method)) {
        return new PutMethod(url);

    } else {/*ww w  . j  a v a2 s  . com*/
        throw ActionException.create(ClientMessages.NO_METHOD1, method);
    }
}