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:models.Calais.java

private PostMethod createPostMethod() {

    PostMethod method = new PostMethod(CALAIS_URL);

    // Set mandatory parameters
    method.setRequestHeader("x-calais-licenseID", "vznmu4gx2njt3hutk6s5typ3");

    // Set input content type
    //method.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
    method.setRequestHeader("Content-Type", "text/html; charset=UTF-8");
    //method.setRequestHeader("Content-Type", "text/raw; charset=UTF-8");

    // Set response/output format
    //method.setRequestHeader("Accept", "xml/rdf");
    //method.setRequestHeader("Accept", "text/simple");
    method.setRequestHeader("Accept", "application/json");

    method.setRequestHeader("calculateRelevanceScore", "true");

    // Enable Social Tags processing
    method.setRequestHeader("enableMetadataType", "SocialTags");

    return method;
}

From source file:edu.htwm.vsp.phoebook.rest.client.RestClient.java

public PhoneUser verifyAddUser(String userName, int expectedStatusCode, String contentType)
        throws IOException, JAXBException, Exception {

    System.out.println("create new PhoneUser: " + userName + " ... \n");
    HttpClient client = new HttpClient();

    // -- build HTTP POST request
    PostMethod method = new PostMethod(getServiceBaseURI() + "/users");
    method.addParameter("name", userName);

    // -- determine the mime type you wish to receive here 
    method.setRequestHeader("Accept", contentType);

    int responseCode = client.executeMethod(method);

    assertEquals(expectedStatusCode, responseCode);

    String response = responseToString(method.getResponseBodyAsStream());
    System.out.println(response);
    String content = method.getResponseHeader("Content-Type").getValue();
    /* Antwort zurckgeben */
    return getUserFromResponse(response, content);

}

From source file:edu.scripps.fl.pubchem.EUtilsFactory.java

public Callable<InputStream> getInputStream(final String url, final Object... params) throws IOException {
    return new Callable<InputStream>() {
        public InputStream call() throws Exception {
            StringBuffer sb = new StringBuffer();
            sb.append(url).append("?");
            PostMethod post = new PostMethod(url);
            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new NameValuePair("tool", EUtilsFactory.this.tool));
            data.add(new NameValuePair("email", EUtilsFactory.this.email));
            for (int ii = 0; ii < params.length; ii += 2) {
                String name = params[ii].toString();
                String value = "";
                if ((ii + 1) < params.length)
                    value = params[ii + 1].toString();
                data.add(new NameValuePair(name, value));
                sb.append(name).append("=").append(value).append("&");
            }/*from  www  .  j a v  a  2s. c  o  m*/
            post.setRequestBody(data.toArray(new NameValuePair[0]));
            HttpClient httpclient = new HttpClient();
            int result = httpclient.executeMethod(post);
            //            log.debug("Fetching from: " + url + StringUtils.join(params, " "));
            log.debug("Fetching from: " + sb);
            InputStream in = post.getResponseBodyAsStream();
            return in;
        }
    };
}

From source file:net.sourceforge.jwbf.actions.mw.util.PostModifyContent.java

/**
 * //from   ww  w  . j  ava  2s .com
 * @param a the
 * @param tab internal value set
 * @param login a 
 */
public PostModifyContent(final ContentAccessable a, final Hashtable<String, String> tab, LoginData login) {

    String uS = "";
    try {
        uS = "/index.php?title=" + URLEncoder.encode(a.getLabel(), MediaWikiBot.CHARSET) + "&action=submit";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    NameValuePair action = new NameValuePair("wpSave", "Save");
    NameValuePair wpStarttime = new NameValuePair("wpStarttime", tab.get("wpStarttime"));
    NameValuePair wpEditToken = new NameValuePair("wpEditToken", tab.get("wpEditToken"));
    NameValuePair wpEdittime = new NameValuePair("wpEdittime", tab.get("wpEdittime"));

    NameValuePair wpTextbox = new NameValuePair("wpTextbox1", a.getText());

    String editSummaryText = a.getEditSummary();
    if (editSummaryText != null && editSummaryText.length() > 200) {
        editSummaryText = editSummaryText.substring(0, 200);
    }

    NameValuePair wpSummary = new NameValuePair("wpSummary", editSummaryText);

    NameValuePair wpMinoredit = new NameValuePair();

    if (a.isMinorEdit()) {
        wpMinoredit.setValue("1");
        wpMinoredit.setName("wpMinoredit");
    }

    LOG.info("WRITE: " + a.getLabel());
    PostMethod pm = new PostMethod(uS);
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);

    pm.setRequestBody(new NameValuePair[] { action, wpStarttime, wpEditToken, wpEdittime, wpTextbox, wpSummary,
            wpMinoredit });
    msgs.add(pm);
}

From source file:de.mpg.escidoc.http.Login.java

private Cookie passSecurityCheck() {
    String loginName = Util.input("Enter Username: ");
    String loginPassword = Util.input("Enter Password: ");
    int delim1 = this.FRAMEWORK_URL.indexOf("//");
    int delim2 = this.FRAMEWORK_URL.indexOf(":", delim1);
    String host;/*from  w w  w  . j  ava  2  s .co m*/
    int port;
    if (delim2 > 0) {
        host = this.FRAMEWORK_URL.substring(delim1 + 2, delim2);
        port = Integer.parseInt(this.FRAMEWORK_URL.substring(delim2 + 1));
    } else {
        host = this.FRAMEWORK_URL.substring(delim1 + 2);
        port = 80;
    }

    PostMethod post = new PostMethod(this.FRAMEWORK_URL + "/aa/j_spring_security_check");
    post.addParameter("j_username", loginName);
    post.addParameter("j_password", loginPassword);
    try {
        this.client.executeMethod(post);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    post.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, this.client.getState().getCookies());
    Cookie sessionCookie = logoncookies[0];
    return sessionCookie;
}

From source file:demo.jaxrs.search.client.Client.java

private static void uploadToCatalog(final String url, final HttpClient httpClient, final String filename)
        throws IOException, HttpException {

    System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename);

    final PostMethod post = new PostMethod(url);
    final Part[] parts = { new FilePart(filename, new ByteArrayPartSource(filename,
            IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename)))) };

    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    try {/*from w w w . j a  v a2  s.co  m*/
        int status = httpClient.executeMethod(post);
        if (status == 201) {
            System.out.println(post.getResponseHeader("Location"));
        } else if (status == 409) {
            System.out.println("Document already exists: " + filename);
        }

    } finally {
        post.releaseConnection();
    }
}

From source file:com.turborep.turbotracker.home.WeatherSer.java

/**
 * This method is used to connect the weather webservice of world weather online.
 * @return weather webservice response as {@link String}
 * @throws WeatherException/*from   ww w .j av  a  2  s.co  m*/
 */
private String connectWebservice() throws WeatherException {
    String aUrlStr = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=" + getZipCode()
            + "&format=json&num_of_days=" + getForecastDays() + "&key=" + getApiKey();
    try {
        /**  ========================= Proxy settings ================================   **/
        /**System.getProperties().put("http.proxyHost", "http://192.168.43.1");
        System.getProperties().put("http.proxyPort", "3128");
        System.getProperties().put("http.proxyUser", "vish_pepala");
        System.getProperties().put("http.proxyPassword", "S@Naidu");
        System.getProperties().put("http.proxySet", "true");
        /******************************************************************/

        PostMethod post = new PostMethod(aUrlStr);
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        HttpClient httpclient = new HttpClient();

        httpclient.executeMethod(post);
        String aResponse = post.getResponseBodyAsString();
        //logger.info(aResponse);
        return aResponse;
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
        WeatherException aWeatherException = new WeatherException(e.getMessage(), e);
        throw aWeatherException;
    } catch (HttpException e) {
        logger.error(e.getMessage(), e);
        WeatherException aWeatherException = new WeatherException(e.getMessage(), e);
        throw aWeatherException;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        WeatherException aWeatherException = new WeatherException(e.getMessage(), e);
        throw aWeatherException;
    }
}

From source file:Controladora.ConexionAPI.java

public String sendPost(String nombre, String pass) {
    httpClient = null; // Objeto a travs del cual realizamos las peticiones
    request = null; // Objeto para realizar las peticiines HTTP GET o POST
    status = 0; // Cdigo de la respuesta HTTP
    reader = null; // Se usa para leer la respuesta a la peticin
    line = null; // Se usa para leer cada una de las lineas de texto de la respuesta
    String token = null;//  w  w  w . j  ava  2 s  . c  om
    String tkn = null;

    // Instanciamos el objeto
    httpClient = new HttpClient();
    // Invocamos por POST
    String url = "http://localhost:8090/login";
    request = new PostMethod(url);
    // Aadimos los parmetros que deseemos a la peticin 
    ((PostMethod) request).addParameter("usuario", nombre);
    ((PostMethod) request).addParameter("password", pass);
    try {
        // Leemos el cdigo de la respuesta HTTP que nos devuelve el servidor
        status = httpClient.executeMethod(request);
        // Vemos si la peticin se ha realizado satisfactoriamente
        if (status != HttpStatus.SC_OK) {
            System.out.println("Error\t" + request.getStatusCode() + "\t" + request.getStatusText() + "\t"
                    + request.getStatusLine());
        } else {
            // Leemos el contenido de la respuesta y realizamos el tratamiento de la misma.
            // En nuestro caso, simplemente mostramos el resultado por la salida estndar
            reader = new BufferedReader(
                    new InputStreamReader(request.getResponseBodyAsStream(), request.getResponseCharSet()));
            line = reader.readLine();
            while (line != null) {
                token = line;
                line = reader.readLine();
            }
            JSONParser parser = new JSONParser();
            JSONObject jo = (JSONObject) parser.parse(token);
            tkn = (String) jo.get("token");
        }
    } catch (Exception ex) {
        System.out.println("Error\t: " + ex.getMessage());
        /*      
              ex.printStackTrace();*/
    } finally {
        // Liberamos la conexin. (Tambin libera los stream asociados)
        request.releaseConnection();
    }
    return tkn;
}

From source file:com.curl.orb.client.ClientUtil.java

Object requestToORB(InstanceManagementRequest request, String uri, boolean hasManyResult)
        throws ORBClientException, ORBServerException {
    AbstractSerializer serializer = SerializerFactory.getInstance().getSerializer();
    OutputStream outputStream = new ByteArrayOutputStream();
    Object returnedObject = null;
    InputStream inputStream = null;
    PostMethod method = null;//  w ww . j  a va 2 s. co  m
    try {
        serializer.serialize(request, null, outputStream);
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        method = new PostMethod(uri);
        method.setRequestHeader("Content-Length", ((ByteArrayOutputStream) outputStream).size() + "");
        method.setRequestEntity(new ByteArrayRequestEntity(((ByteArrayOutputStream) outputStream).toByteArray(),
                "application/octet-stream; charset=UTF-8"));
        httpClient.executeMethod(method);
        method.getResponseBody();
        inputStream = (ByteArrayInputStream) method.getResponseBodyAsStream();
        SerializableStreamReader deserializer = new CurlSerializableStreamReader(inputStream);
        returnedObject = ((InstanceManagementResponse) deserializer.read()).getBody();
        if (hasManyResult) {
            List<Object> resultList = new ArrayList<Object>();
            resultList.add(returnedObject);
            Object innerresult = null;
            while ((innerresult = deserializer.read()) != null)
                resultList.add(innerresult);
            return resultList;
        }
        if (returnedObject instanceof ExceptionContent) {
            throw new ORBServerException((ExceptionContent) returnedObject);
        }
    } catch (SerializerException e) {
        throw new ORBClientException(e);
    } catch (HttpException e) {
        throw new ORBClientException(e);
    } catch (IOException e) {
        throw new ORBClientException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new ORBClientException(e);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new ORBClientException(e);
                    }
                }
                method.releaseConnection();
            }
        }
    }
    return returnedObject;
}

From source file:com.jackbe.mapreduce.RESTClient.java

public void executeREST(String encodedValue) {
    String result = null;// www  .  j a  v  a 2 s.co  m
    String postPath = protocol + host + ":" + port + path;
    System.out.println("post path = " + postPath);
    PostMethod pm = new PostMethod(postPath);
    System.out.println("10 Encoded value = \n" + encodedValue);
    if (encodedValue != null) {
        //httpMethod = new PostMethod(protocol + host + ":" + port + path);
        //InputStream is = new ByteArrayInputStream(encodedValue.getBytes());
        //pm.setRequestBody(is);
        pm.setRequestBody(encodedValue);
        System.out.println("Validate = " + pm.validate());
        //pm.setQueryString(encodedValue);

        //pm.setHttp11(false);

        log.debug("Invoking REST service: " + protocol + host + ":" + port + path + " " + pm.toString());

    } else {
        throw new RuntimeException("EncodedValue can't be null");
    }

    try {
        client.executeMethod(pm);

        if (pm.getStatusCode() != HttpStatus.SC_OK) {
            log.error("HTTP Error status connecting to Presto: " + pm.getStatusCode());
            log.error("HTTP Error message connecting to Presto: " + pm.getStatusText());
            return;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Status code: " + pm.getStatusCode());
                Header contentTypeHeader = pm.getResponseHeader("content-type");
                log.debug("Mimetype: " + contentTypeHeader.getValue());
            }
        }

        result = pm.getResponseBodyAsString();
        // log.debug(httpMethod.getStatusText());
        if (log.isDebugEnabled())
            log.debug("Response: " + result);
    } catch (Exception e) {
        log.error("Exception executing REST call: " + e, e);
    } finally {
        pm.releaseConnection();
    }
}