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.intellij.tasks.fogbugz.FogBugzRepository.java

private Task[] getCases(String q) throws Exception {
    HttpClient client = login(getLoginMethod());
    PostMethod method = new PostMethod(getUrl() + "/api.asp");
    method.addParameter("token", token);
    method.addParameter("cmd", "search");
    method.addParameter("q", q);
    method.addParameter("cols", "sTitle,fOpen,dtOpened,dtLastUpdated,ixCategory");
    int status = client.executeMethod(method);
    if (status != 200) {
        throw new Exception("Error listing cases: " + method.getStatusLine());
    }/*from   ww  w  .  j  a  v a2 s.co  m*/
    Document document = new SAXBuilder(false).build(method.getResponseBodyAsStream()).getDocument();
    XPath path = XPath.newInstance("/response/cases/case");
    final XPath commentPath = XPath.newInstance("events/event");
    @SuppressWarnings("unchecked")
    final List<Element> nodes = (List<Element>) path.selectNodes(document);
    final List<Task> tasks = ContainerUtil.mapNotNull(nodes, new NotNullFunction<Element, Task>() {
        @Nonnull
        @Override
        public Task fun(Element element) {
            return createCase(element, commentPath);
        }
    });
    return tasks.toArray(new Task[tasks.size()]);
}

From source file:com.predic8.membrane.core.transport.http.ServiceInvocationTest.java

private PostMethod createPostMethod() {
    PostMethod post = new PostMethod("http://localhost:3016/axis2/services/BLZService?wsdl");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml")));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");
    return post;/*from w ww  .j  a  va2 s. com*/
}

From source file:guru.nidi.atlassian.remote.script.RemoteConfluence.java

Object executeImpl(String command, Object... parameters) throws RpcException {
    PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/confluenceservice-v2/" + command);
    post.setRequestHeader("Content-Type", "application/json");
    HttpUtils.setAuthHeader(post, username, password);
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//ww  w.  jav  a 2 s.c o m
        mapper.writeValue(baos, parameters);
        post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("not ok");
        }
        try {
            ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    ErrorResponse.class);
            throw new RpcException(errorResponse);
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        try {
            return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    new TypeReference<HashMap<String, Object>>() {
                    });
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                new TypeReference<ArrayList<Object>>() {
                });
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return null;
}

From source file:jshm.sh.client.HttpForm.java

/**
 * //from  w  w w . j  av a  2 s  . com
 * @param method Is an {@link Object} for the purpose of overloading the constructor
 * @param url
 * @param data An array of Strings with alternating keys and values
 */
public HttpForm(final String method, final Object url, final String... data) {
    if ((data.length & 1) != 0)
        throw new IllegalArgumentException("data must have an even number of values");
    if (!(url instanceof String))
        throw new IllegalArgumentException("url must be a String");

    this.url = (String) url;
    this.data = new NameValuePair[data.length / 2];

    // this.data[0] = data[0], data[1]
    // this.data[1] = data[2], data[3]
    // this.data[2] = data[4], data[5]
    for (int i = 0; i < data.length; i += 2) {
        this.data[i / 2] = new NameValuePair(data[i], data[i + 1]);
    }

    this.methodName = method;

    if ("POST".equalsIgnoreCase(method.toString())) {
        PostMethod postMethod = new PostMethod(this.url);
        postMethod.setRequestBody(this.data);
        this.method = postMethod;
    } else if ("GET".equalsIgnoreCase(method.toString())) {
        GetMethod getMethod = new GetMethod(this.url);
        getMethod.setQueryString(this.data);
        this.method = getMethod;
    } else {
        throw new IllegalArgumentException("method must be POST or GET, given: " + method);
    }
}

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

/**
 * ?url??post//w  w w .  j  a v  a  2  s.  c o  m
 * 
 * @param url
 * @param paramsStr
 *            ?
 * @param method
 * @return String ?
 */
public static String post(String url, String paramsStr, String method) {

    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);
    httpMethod.setQueryString(paramsStr);
    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            return httpMethod.getResponseBodyAsString();
        } 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);
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

From source file:jenkins.plugins.office365connector.HttpWorker.java

@Override
public void run() {
    int tried = 0;
    boolean success = false;
    HttpClient client = getHttpClient();
    client.getParams().setConnectionManagerTimeout(timeout);
    do {/*from w  w  w  .  j av  a 2s  .c o m*/
        tried++;
        RequestEntity requestEntity;
        try {
            // uncomment to log what message has been sent
            // log("Posted JSON: %s", data);
            requestEntity = new StringRequestEntity(data, "application/json", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(logger);
            break;
        }

        PostMethod post = new PostMethod(url);
        try {
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            if (responseCode != HttpStatus.SC_OK) {
                String response = post.getResponseBodyAsString();
                log("Posting data to %s may have failed. Webhook responded with status code - %s", url,
                        responseCode);
                log("Message from webhook - %s", response);

            } else {
                success = true;
            }
        } catch (IOException e) {
            log("Failed to post data to webhook - %s", url);
            e.printStackTrace(logger);
        } finally {
            post.releaseConnection();
        }
    } while (tried < RETRIES && !success);

}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java

public HashMap<String, String> doPost(String relativeServiceURL) {

    PostMethod post = null;//from ww  w .  ja  v a  2s  .  c  om
    HttpClient httpclient = new HttpClient();
    String requestString = "";
    HashMap<String, String> responseMap = new HashMap<String, String>();

    try {
        // the client id and secret is applicable across all dev orgs
        requestString = generateRequestString();
        String authorizationServerURL = CommandLineArguments.getOrgUrl() + relativeServiceURL;

        httpclient.getParams().setSoTimeout(0);
        post = new PostMethod(authorizationServerURL);
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addRequestHeader("X-PrettyPrint", "1");
        post.setRequestEntity(
                new StringRequestEntity(requestString, "application/x-www-form-urlencoded", "UTF-8"));
        httpclient.executeMethod(post);

        Gson json = new Gson();
        // obtain the result map from the response body and get the access
        // token
        responseMap = json.fromJson(post.getResponseBodyAsString(), new TypeToken<HashMap<String, String>>() {
        }.getType());

    } catch (Exception ex) {
        ApexUnitUtils.shutDownWithDebugLog(ex, "Exception during post method: " + ex);
        if (LOG.isDebugEnabled()) {
            ex.printStackTrace();
        }
    } finally {
        post.releaseConnection();
    }

    return responseMap;

}

From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }/*from ww w  .j  a va 2s  . com*/
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:com.google.wave.api.robot.HttpRobotConnection.java

@Override
public String postJson(String url, String body) throws RobotConnectionException {
    PostMethod method = new PostMethod(url);
    try {//from   w  ww  .  j  a  v a2 s  .  c o  m
        method.setRequestEntity(
                new StringRequestEntity(body, RobotConnection.JSON_CONTENT_TYPE, Charsets.UTF_8.name()));
        return fetch(url, method);
    } catch (IOException e) {
        String msg = "Robot fetch http failure: " + url + ": " + e;
        throw new RobotConnectionException(msg, e);
    }
}

From source file:com.voidsearch.voidbase.client.VoidBaseHttpClient.java

protected void post(VoidBaseQuery query, String content) throws Exception {

    PostMethod post = new PostMethod(query.getQuery());
    post.setRequestBody(content);//from   ww  w  .  j a v  a  2  s.  c  o m

    try {
        client.executeMethod(post);
        post.getResponseBodyAsStream(); // ignore response
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}