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:ixa.entity.linking.DBpediaSpotlightClient.java

public Document extract(Text text, int port) throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse = "";
    Document doc = null;/*from   w ww.  ja  va2  s  .  com*/
    try {
        String url = "http://localhost:" + port + "/rest/disambiguate";
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        NameValuePair[] params = { new NameValuePair("text", text.text()),
                new NameValuePair("spotter", "SpotXmlParser"),
                new NameValuePair("confidence", Double.toString(CONFIDENCE)),
                new NameValuePair("support", Integer.toString(SUPPORT)) };
        method.setRequestBody(params);
        method.setRequestHeader(new Header("Accept", "text/xml"));
        spotlightResponse = request(method);
        doc = loadXMLFromString(spotlightResponse);
    } catch (javax.xml.parsers.ParserConfigurationException ex) {
    } catch (org.xml.sax.SAXException ex) {
    } catch (java.io.IOException ex) {
    }

    return doc;
}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs an HTTP request against an URL.
 *
 * @param url         the URL to call/*from  w  ww  . j  a v  a2  s .  c om*/
 * @param method      the HTTP method to execute
 * @param body        the body of a POST or PUT request, can be <code>null</code>
 * @param queryParams a Hash with the query parameter, can be <code>null</code>
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 */
@SuppressWarnings("deprecation")
public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) {

    NameValuePair[] query = null;

    if (queryParams != null) {
        query = new NameValuePair[queryParams.size()];

        int counter = 0;
        for (Entry<String, String> queryParam : queryParams.entrySet()) {
            query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue());
            counter++;
        }
    }

    org.apache.commons.httpclient.HttpMethod request = null;

    if (method == HttpMethod.GET) {
        request = new GetMethod(url);
    } else if (method == HttpMethod.POST) {
        PostMethod postRequest = new PostMethod(url);
        if (body != null) {
            postRequest.setRequestBody(body);
        }
        request = postRequest;
    } else if (method == HttpMethod.PUT) {
        PutMethod putRequest = new PutMethod(url);
        if (body != null) {
            putRequest.setRequestBody(body);
        }
        request = putRequest;
    } else if (method == HttpMethod.DELETE) {
        request = new DeleteMethod(url);
    }

    request.setRequestHeader("Content-type", "application/xml;charset=utf-8");
    if (query != null) {
        request.setQueryString(query);
    }

    int resultCode = 0;
    StringBuilder resultBodyBuilder = new StringBuilder();

    try {
        resultCode = this.httpClient.executeMethod(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8")));
        String line = null;
        while ((line = reader.readLine()) != null) {
            resultBodyBuilder.append(line);
        }

        if (resultCode != 200) {
            throw new HttpException(resultBodyBuilder.toString(), null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP request failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP request failed", ioException);
    } catch (NullPointerException npe) {
        throw new HttpException("HTTP request failed", npe);
    } finally {
        request.releaseConnection();
    }

    return resultBodyBuilder.toString();
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    onRequest().havingRawBodyEqualTo(BINARY_BODY).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    final int status = client.executeMethod(method);
    assertThat(status, is(201));/*from w  w  w .j  a  va2  s .  c  om*/
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

/**
 * @see {@link GraphRepository#create(String)}
 *///  ww  w  . java2s  . c o  m
public void create(String rdfXml) throws Exception {

    // POST
    PostMethod post = new PostMethod(servletURL);
    try {

        // set the body
        if (rdfXml != null) {
            post.setRequestEntity(new StringRequestEntity(rdfXml, // the rdf/xml body
                    GraphRepositoryServlet.RDF_XML, // includes the encoding
                    null // so we don't need to say it here.
            ));
            post.setContentChunked(true);
        }

        // Execute the method.
        int sc = getHttpClient().executeMethod(post);
        if (sc != HttpStatus.SC_OK) {
            throw new IOException("HTTP-POST failed: " + post.getStatusLine());
        }

    } finally {
        // Release the connection.
        post.releaseConnection();
    }

}

From source file:com.bakhtiyor.android.tumblr.TumblrService.java

private void uploadPhoto(String email, String password, String caption, boolean isPrivate, String filename) {
    try {//from   w  w w. j  a v a2 s . c  om
        File file = new File(filename);
        final HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        final PostMethod multipartPost = new PostMethod(API_URL);
        Part[] parts = { new StringPart(FIELD_EMAIL, email), new StringPart(FIELD_PASSWORD, password),
                new StringPart(FIELD_TYPE, "photo"), new StringPart("generator", GENERATOR),
                new StringPart(FIELD_CAPTION, caption), new StringPart(FIELD_PRIVATE, isPrivate ? "1" : "0"),
                new FilePart("data", file) };
        multipartPost.setRequestEntity(new MultipartRequestEntity(parts, multipartPost.getParams()));
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        int id = new Random().nextInt();
        showUploadingNotification(id);
        int status = httpClient.executeMethod(multipartPost);
        clearNotification(id);
        if (status == 201) {
            showResultNotification("Successful Uploaded");
        } else {
            showResultNotification("Error occured");
        }
    } catch (Throwable e) {
        Log.e(TAG, e.getMessage(), e);
    }
}

From source file:edu.usc.corral.api.Client.java

public <T> T doPost(String path, Class<? extends T> responseType, Object request) throws GlideinException {
    ensureOpen();// w  w w .  j  a  va  2  s . c o m

    Serializer serializer = new Persister();
    RequestEntity entity = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.write(request, baos);
        entity = new ByteArrayRequestEntity(baos.toByteArray(), "text/xml");
    } catch (Exception e) {
        throw new GlideinException("Unable to generate request xml", e);
    }

    PostMethod post = new PostMethod(path);
    try {
        post.setRequestEntity(entity);
        int status = httpclient.executeMethod(post);
        InputStream is = post.getResponseBodyAsStream();
        if (status < 200 || status > 299) {
            handleError(is);
        }
        return serializer.read(responseType, is);
    } catch (HttpException he) {
        throw new GlideinException("Error parsing http", he);
    } catch (IOException ioe) {
        throw new GlideinException("Error communicating with server", ioe);
    } catch (GlideinException ge) {
        throw ge;
    } catch (Exception e) {
        throw new GlideinException("Unable to parse response xml", e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.zb.app.external.wechat.service.WeixinService.java

public void upload(File file, String type) {
    StringBuilder sb = new StringBuilder(400);
    sb.append("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=");
    sb.append(getAccessToken());// ww w  .  j a v  a 2  s .  c  om
    sb.append("&type=").append(type);

    PostMethod postMethod = new PostMethod(sb.toString());
    try {
        // FilePart?
        FilePart fp = new FilePart("filedata", file);
        Part[] parts = { fp };
        // MIMEhttpclientMulitPartRequestEntity
        MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
        postMethod.setRequestEntity(mre);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.error(postMethod.getResponseBodyAsString());
        } else {
            logger.error("fail");
        }
        byte[] responseBody = postMethod.getResponseBody();
        String result = new String(responseBody, "utf-8");
        logger.error("result : " + result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        postMethod.releaseConnection();
    }
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

private void preparePostMethod(HttpServletRequest httpServletRequest) throws IOException {

    // Create a standard POST request
    PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest));
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    // Check if this is a mulitpart (file upload) POST
    if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
        this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
    } else {//  w  ww .ja v  a  2 s  .  c  om
        this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
    }

    this.httpMethod = postMethodProxyRequest;
}