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.ebt.platform.utility.WebServiceCaller.java

private static String CallDatv2WebService(String xml) {
    PostMethod postMethod = new PostMethod("http://datv2.e-baotong.cn:9089/GetVersionData.asmx?wsdl");
    String responseString = null;
    try {//from  w  w  w .  j av a 2s . com
        byte[] b = xml.getBytes("utf-8");
        InputStream inS = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity req = new InputStreamRequestEntity(inS, b.length, "text/xml; charset=utf-8");
        postMethod.setRequestEntity(req);

        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == 200) {
            responseString = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("WebService??====" + responseString);
        } else {
            System.out.println("WebService??" + statusCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseString;
}

From source file:com.infosupport.service.LPRServiceCaller.java

public static void postData(String urlString, File file) {
    try {/* www .ja  v  a2s. c om*/
        PostMethod postMessage = new PostMethod(urlString);
        Part[] parts = { new FilePart("lpimage", file), new StringPart("country", "eu"),
                new StringPart("nonce", "123456789") };
        postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
        HttpClient client = new HttpClient();
        client.executeMethod(postMessage);
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
}

From source file:net.bioclipse.opentox.api.ModelAlgorithm.java

@SuppressWarnings("serial")
public static String calculate(String service, String model, String dataSetURI, IProgressMonitor monitor)
        throws HttpException, IOException, InterruptedException, GeneralSecurityException {
    if (monitor == null)
        monitor = new NullProgressMonitor();
    int worked = 0;

    HttpClient client = new HttpClient();
    dataSetURI = Dataset.normalizeURI(dataSetURI);
    PostMethod method = new PostMethod(model);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {/*ww w  . j  av a2 s. c om*/
            put("Accept", "text/uri-list");
        }
    });
    method.setParameter("dataset_uri", dataSetURI);
    method.setParameter("dataset_service", service + "dataset");
    client.executeMethod(method);
    int status = method.getStatusCode();
    String dataset = "";
    // FIXME: I should really start using the RDF response...
    String responseString = method.getResponseBodyAsString();
    logger.debug("Status: " + status);
    int tailing = 1;
    if (status == 200 || status == 202) {
        if (responseString.contains("/task/")) {
            // OK, we got a task... let's wait until it is done
            String task = responseString;
            logger.debug("response: " + task);
            Thread.sleep(andABit(500)); // let's be friendly, and wait 1 sec
            TaskState state = Task.getState(task);
            while (!state.isFinished() && !monitor.isCanceled()) {
                int onlineWorked = (int) state.getPercentageCompleted();
                if (onlineWorked > worked) {
                    // work done is difference between done before and online done
                    monitor.worked(onlineWorked - worked);
                    worked = onlineWorked;
                }
                // let's be friendly, and wait 2 secs and a bit and increase
                // that time after each wait
                int waitingTime = andABit(2000 * tailing);
                logger.debug("Waiting " + waitingTime + "ms.");
                waitUnlessInterrupted(waitingTime, monitor);
                state = Task.getState(task);
                if (state.isRedirected()) {
                    task = state.getResults();
                    logger.debug("Got a Task redirect. New task:" + task);
                }
                // but wait at most 20 secs and a bit
                if (tailing < 10)
                    tailing++;
            }
            if (monitor.isCanceled())
                Task.delete(task);
            // OK, it should be finished now
            dataset = state.getResults();
        } else {
            // OK, that was quick!
            dataset = responseString;
            logger.debug("No Task, Data set: " + dataset);
            monitor.worked(100);
        }
    } else if (status == 401) {
        throw new GeneralSecurityException("Not authenticated");
    } else if (status == 403) {
        throw new GeneralSecurityException("Not authorized");
    } else if (status == 404) {
        logger.debug("Model not found (404): " + responseString);
        throw new UnsupportedOperationException("Service not found");
    } else {
        logger.debug("Model error (" + status + "): " + responseString);
        throw new IllegalStateException("Service error: " + status);
    }
    method.releaseConnection();
    dataset = dataset.replaceAll("\n", "");
    return dataset;
}

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

public String[] getUsers(String authName) throws BadRequestException, InternalServerErrorException, IOException,
        UnauthorizedException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/all/withAccess");
    postMethod.addParameter("authName", authName);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_ACCEPTED:
        String response = XMLHelper.fromStreamToXML(postMethod.getResponseBodyAsStream());
        StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);
        List<String> ls = new ArrayList<>();
        lc.getContainer().stream().forEach(obj -> {
            Gson gson = new Gson();
            ls.add(obj);/*from ww  w .  ja  va  2s . com*/
        });
        return ls.toArray(new String[ls.size()]);
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_UNAUTHORIZED:
        throw new UnauthorizedException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:eu.europeana.sip.licensing.network.LicenseServiceImpl.java

@Override
public License requestLicense(Answers answers) throws IOException {
    LOG.info(String.format("Sending request to server%n%s", answers.toXML()));
    PostMethod postMethod = new PostMethod(CC_ISSUE);
    postMethod.addParameter("answers", answers.toXML());
    int result = httpClient.executeMethod(postMethod);
    XStream xStream = new XStream(new DomDriver()); // todo: do we need a domdriver?
    xStream.setClassLoader(CustomClassLoader.getInstance());
    xStream.processAnnotations(License.class);
    LOG.info(String.format("Got response from server : %d %n%s", result, postMethod.getResponseBodyAsString()));
    return (License) xStream.fromXML(postMethod.getResponseBodyAsString());
}

From source file:es.carebear.rightmanagement.client.group.GetUserlistGroup.java

public String[] GetUserlist(String targetGroup, String authName)
        throws IOException, UnauthorizedException, BadRequestException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/groups/users/" + targetGroup);
    postMethod.addParameter("authName", authName);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_ACCEPTED:
        String response = XMLHelper.fromStreamToXML(postMethod.getResponseBodyAsStream());
        StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);
        List<String> ls = new ArrayList<>();
        lc.getContainer().stream().forEach(obj -> {
            ls.add(obj);/*from w w  w  .  ja  va 2  s  . co m*/
        });
        return ls.toArray(new String[ls.size()]);
    case HttpStatus.SC_FORBIDDEN:
        throw new UnauthorizedException();
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:es.carebear.rightmanagement.client.group.GetGroupListOfUser.java

public ArrayList<Group> getGroups(String authName, String userName) throws IOException, UnauthorizedException,
        BadRequestException, UnknownResponseException, ClassNotFoundException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/groups/all/" + userName);
    postMethod.addParameter("authName", authName);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_ACCEPTED:
        String response = XMLHelper.fromStreamToXML(postMethod.getResponseBodyAsStream());

        StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);
        List<Group> ls = new ArrayList<>();
        lc.getContainer().stream().forEach(obj -> {
            Gson gson = new Gson();
            ls.add(gson.fromJson(obj, Group.class));
        });//from   ww w  .j a  v a2 s .  c o m
        return (ArrayList<Group>) ls;
    case HttpStatus.SC_FORBIDDEN:
        throw new UnauthorizedException();
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

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

public String[] getRights(String authName)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/all/withRigthOnUser");
    postMethod.addParameter("authName", authName);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_ACCEPTED:
        String response = XMLHelper.fromStreamToXML(postMethod.getResponseBodyAsStream());
        StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);
        List<String> ls = new ArrayList<>();
        lc.getContainer().stream().forEach(obj -> {
            Gson gson = new Gson();
            ls.add(obj);/*from   w  w  w.j a va  2  s  . c  o  m*/
        });
        return ls.toArray(new String[ls.size()]);
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:com.swdouglass.joid.server.ReCaptcha.java

/**
 * This method posts the four parameters necessary to solve a
 * <a href="http://recaptcha.net/apidocs/captcha/">captcha</a>.
 * /*from ww w  . jav  a2 s  .  co  m*/
 * @param privateKey Your recaptcha private key
 * @param remoteAddr The IP address of the end user
 * @param challenge The mangled text displayed
 * @param response Then end-user's interpretation of that text
 * @return null if successful, error message if not
 */
public static String check(String privateKey, String remoteAddr, String challenge, String response) {
    String message = null;
    String str = null;
    if (challenge == null || response == null) {
        message = "Challenge and response strings can't be null!";
    } else {
        try {

            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(VERIFY_URL);
            post.addParameter("privatekey", privateKey);
            post.addParameter("remoteip", remoteAddr);
            post.addParameter("challenge", challenge);
            post.addParameter("response", response);
            client.executeMethod(post);
            BufferedReader in = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            str = in.readLine(); // read the first line of the response
            if (str == null) {
                message = "Null read from server."; // treat this as not verfied
            } else {
                boolean valid = "true".equals(str);
                if (!valid) {
                    str = in.readLine(); // get next line which has message
                    if (str.length() > 1) {
                        message = str;
                    } else {
                        message = "missing error message?";
                    }
                }
            }

        } catch (IOException ex) {
            log.error(ex);
            ex.printStackTrace();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Response: " + str);
    }
    return message;
}

From source file:com.atlassian.jira.web.action.setup.SetupProductBundleHelper.java

public void authenticateUser(final String username, final String password) {
    final HttpClient httpClient = prepareClient();
    final PostMethod method = new PostMethod(getAuthenticationUrl());

    try {//from   ww w  .  j a va 2s .c  om
        final StringRequestEntity requestEntity = new StringRequestEntity(
                prepareJSON(ImmutableMap.of("username", username, "password", password)), "application/json",
                "UTF-8");

        method.setRequestEntity(requestEntity);

        final int status = httpClient.executeMethod(method);
        if (status == 200) {
            saveCookies(httpClient.getState().getCookies());
        } else {
            log.warn("Problem authenticating user during product bundle license installation, status code: "
                    + status);
        }
    } catch (final IOException e) {
        log.warn("Problem authenticating user during product bundle license installation", e);
    } finally {
        method.releaseConnection();
    }
}