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:edu.ku.brc.services.biogeomancer.BioGeomancer.java

/**
 * Sends a georeferencing request to the BioGeomancer web service.
 * //from w  ww  . j ava 2  s  .  c  o m
 * @param id id
 * @param country country
 * @param adm1 country
 * @param adm2 adm2
 * @param localityArg locality
 * @return returns the response body content (as XML)
 * @throws IOException a network error occurred while contacting the BioGeomancer service
 */
public static String getBioGeomancerResponse(final String id, final String country, final String adm1,
        final String adm2, final String localityArg) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod("http://130.132.27.130/cgi-bin/bgm-0.2/batch_test.pl"); //$NON-NLS-1$
    StringBuilder strBuf = new StringBuilder(128);
    strBuf.append("\"" + id + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + country + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + adm1 + "\","); //$NON-NLS-1$ //$NON-NLS-2$
    strBuf.append("\"" + (adm2 != null ? adm2 : "") + "\","); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    strBuf.append("\"" + localityArg + "\"\r\n"); //$NON-NLS-1$ //$NON-NLS-2$

    NameValuePair[] postData = {
            //new NameValuePair("batchtext", "\"12931\",\"Mexico\",\"Veracruz\",\"\",\"12 km NW of Catemaco\"\r\n"),
            new NameValuePair("batchtext", strBuf.toString()), //$NON-NLS-1$
            new NameValuePair("format", "xml") }; //$NON-NLS-1$ //$NON-NLS-2$

    // the 2.0 beta1 version has a
    // PostMethod.setRequestBody(NameValuePair[])
    // method, as addParameters is deprecated
    postMethod.addParameters(postData);

    httpClient.executeMethod(postMethod);

    InputStream iStream = postMethod.getResponseBodyAsStream();

    StringBuilder sb = new StringBuilder();
    byte[] bytes = new byte[8196];
    int numBytes = 0;
    do {
        numBytes = iStream.read(bytes);
        if (numBytes > 0) {
            sb.append(new String(bytes, 0, numBytes));
        }

    } while (numBytes > 0);

    //release the connection used by the method
    postMethod.releaseConnection();

    return sb.toString();
}

From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java

/**
 * //from  w  w w .j  a  v  a  2 s  . c o  m
 * 
 * @param filename
 */
public void upload(String filename, QQUser user) {
    HttpClient client = new HttpClient();
    HostConfiguration conf = new HostConfiguration();
    conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD);
    client.setHostConfiguration(conf);
    PostMethod method = new PostMethod("/cgi-bin/cface/upload");
    method.addRequestHeader("Accept", "*/*");
    method.addRequestHeader("Pragma", "no-cache");

    StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ()));
    uid.setContentType(null);
    uid.setTransferEncoding(null);

    //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7");
    //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040");
    StringPart clientkey = new StringPart("clientkey",
            "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67");
    //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16");
    //      StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey()));
    clientkey.setContentType(null);
    clientkey.setTransferEncoding(null);

    //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875");
    //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62");
    //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA");
    StringPart sign = new StringPart("sign",
            "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764");
    sign.setContentType(null);
    sign.setTransferEncoding(null);

    FilePart file;
    try {
        file = new FilePart("customfacefile", filename, new File(filename));
    } catch (FileNotFoundException e) {
        return;
    }

    Part[] parts = new Part[] { uid, clientkey, sign, file };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());

    method.setRequestEntity(entity);
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            Header header = method.getResponseHeader("CFace-Msg");
            System.out.println(header.getValue());
            header = method.getResponseHeader("CFace-RetCode");
            System.out.println(header.getValue());
        }
    } catch (HttpException e) {
        return;
    } catch (IOException e) {
        return;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.thoughtworks.go.helpers.HttpClientHelper.java

private HttpMethod doRequest(String path, RequestMethod methodRequired, String params) throws IOException {
    HttpMethod method = null;//  w w w  .j  ava  2s. c o m
    String url = baseUrl + path;
    switch (methodRequired) {
    case PUT:
        method = new PutMethod(url);
        break;
    case POST:
        method = new PostMethod(url);
        break;
    case GET:
        method = new GetMethod(url);
        break;
    }
    method.setQueryString(params);
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    return method;
}

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

public void AddUser(String authName, String target, String rigthTarget, String rightMask)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/allowed/" + target);
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("rigthTarget", rigthTarget);
    postMethod.addParameter("rightMask", rightMask);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;//from  www. j a v  a 2s  .c om
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:javaapplicationclientrest.ControllerCliente.java

public void cadastrarNoticia(String titulo, String autor, String conteudo) {
    PostMethod p = new PostMethod(Constants.POST_NOTICIA);
    String xml = "<?xml version=\"1.0\"?>";
    xml += "<noticia><titulo>" + titulo + "</titulo><autor>" + autor + "</autor><conteudo>" + conteudo
            + "</conteudo></noticia>";
    StringRequestEntity requestEntity;/*from ww  w.ja va 2  s  .com*/
    try {
        requestEntity = new StringRequestEntity(xml, "application/xml", "UTF-8");

        p.setRequestEntity(requestEntity);

        try {

            http.executeMethod(p);
            System.out.println("status : " + p.getStatusText());
            //                System.out.println("status: "+ p.getStatusText() + "\n");
            // System.out.println("message: "+ p.getResponseBodyAsString());
        } catch (IOException ex) {
            Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.taobao.metamorphosis.client.http.SimpleHttpProducer.java

/**
 * //from  www .  j  a v a  2s.  c o  m
 * 
 * @param message
 * @throws MetaClientException
 */
public SendResult sendMessage(final Message message, final Partition partition) throws MetaClientException {
    final long start = System.currentTimeMillis();
    this.checkMessage(message);
    final int flag = MessageFlagUtils.getFlag(message);
    final byte[] data = SimpleMessageProducer.encodeData(message);
    final String uri = "/put/" + partition.getBrokerId() + "?topic=" + message.getTopic() + "&partition="
            + partition.getPartition() + "&flag=" + flag + "&length=" + data.length;
    final PostMethod postMethod = new PostMethod(uri);
    try {
        postMethod.setRequestEntity(new ByteArrayRequestEntity(data));
        this.httpclient.executeMethod(postMethod);
        final String resultStr = postMethod.getResponseBodyAsString();
        switch (postMethod.getStatusCode()) {
        case HttpStatus.Success: {
            // messageId partition offset
            final String[] tmps = RESULT_SPLITER.split(resultStr);
            // idid
            MessageAccessor.setId(message, Long.parseLong(tmps[0]));
            return new SendResult(true, new Partition(0, Integer.parseInt(tmps[1])), Long.parseLong(tmps[2]),
                    null);
        }
        case HttpStatus.Forbidden: {
            // ,
            return new SendResult(false, null, -1, String.valueOf(HttpStatus.Forbidden));
        }
        default:
            return new SendResult(false, null, -1, resultStr);
        }
    } catch (final Exception e) {
        this.logger.error(e.getMessage(), e);
        throw new MetaClientException(e);
    } finally {
        final long duration = System.currentTimeMillis() - start;
        System.out.println(duration);
        MetaStatLog.addStatValue2(null, StatConstants.PUT_TIME_STAT, message.getTopic(), duration);
        postMethod.releaseConnection();
    }

}

From source file:com.mrfeinberg.translation.plugin.altavista.AltavistaTranslationService.java

@Override
protected HttpMethod getHttpMethod(final String phrase, final LanguagePair lp) {
    final PostMethod post = new PostMethod("http://babelfish.yahoo.com/translate_txt");
    post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8");
    final NameValuePair[] params = new NameValuePair[] { new NameValuePair("doit", "done"),
            new NameValuePair("ei", "UTF-8"), new NameValuePair("intl", "1"),
            new NameValuePair("trtext", phrase),
            new NameValuePair("lp", LANGUAGES.get(lp.a()) + "_" + LANGUAGES.get(lp.b())), };
    post.setRequestBody(params);/*  w  w  w. j  a  v  a2s  .c o  m*/
    return post;
}

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

Object executeImpl(String command, Object... parameters) throws RpcException {
    PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/jirasoapservice-v2/" + command);
    post.setRequestHeader("Content-Type", "application/json");
    HttpUtils.setAuthHeader(post, username, password);
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   w w  w.ja  v a2  s .co  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: " + status + " " + post.getResponseBodyAsString(MAX_RESPONSE_SIZE));
        }
        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
        }
        try {
            return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    new TypeReference<ArrayList<Object>>() {
                    });
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), String.class);
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return null;
}

From source file:com.testmax.uri.HttpRestWithXmlBody.java

public String handleHTTPPostUnit() {

    String xmlData = "";
    String resp = "";
    // Get target URL
    String strURL = this.url;
    URLConfig urlConf = this.page.getURLConfig();

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

    // Request content will be retrieved directly
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified

    // Specify content type and encoding
    // If content encoding is not explicitly specified
    // ISO-8859-1 is assumed

    Set<String> s = urlConf.getUrlParamset();
    for (String param : s) {
        xmlData = urlConf.getUrlParamValue(param);
        if (param.equalsIgnoreCase("body")) {
            //xmlData=urlConf.getUrlParamValue(param);
            byte buf[] = xmlData.getBytes();
            ByteArrayInputStream in = new ByteArrayInputStream(buf);
            post.setRequestEntity(new InputStreamRequestEntity(new BufferedInputStream(in), xmlData.length()));

        } else {//from w  w  w.ja  v  a  2 s. c  om
            post.setRequestHeader(param, xmlData);
        }
        WmLog.printMessage(">>> Setting URL Param " + param + "=" + xmlData);
    }
    // Get HTTP client
    org.apache.commons.httpclient.HttpClient httpsclient = new org.apache.commons.httpclient.HttpClient();

    // Execute request
    try {

        int response = -1;
        //set the time for this HTTP request
        this.startRecording();
        long starttime = this.getCurrentTime();
        try {
            response = httpsclient.executeMethod(post);
            resp = post.getResponseBodyAsString();
            Header[] heads = post.getResponseHeaders();
            this.cookies = httpsclient.getState().getCookies();

            String header = "";
            for (Header head : heads) {
                header += head.getName() + ":" + head.getValue();
            }
            System.out.println("Header=" + header);

        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Measure the time passed between response
        long elaspedTime = this.getElaspedTime(starttime);
        this.stopRecording(response, elaspedTime);

        System.out.println(resp);
        System.out.println("ElaspedTime: " + elaspedTime);
        WmLog.printMessage("Response XML: " + resp);
        WmLog.printMessage("ElaspedTime: " + elaspedTime);
        this.printRecording();
        this.printLog();
        if (response == 200 || response == 400) {
            this.addThreadActionMonitor(this.action, true, elaspedTime);
        } else {
            this.addThreadActionMonitor(this.action, false, elaspedTime);
            WmLog.printMessage("Input XML: " + xmlData);
            WmLog.printMessage("Response XML: " + resp);
        }
        if (resp.contains("{") && resp.contains("}") && resp.contains(":")) {
            try {
                resp = "{  \"root\": " + resp + "}";
                HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
                HierarchicalStreamDriver jsonXmlDriver = new JettisonMappedXmlDriver();
                StringWriter strWriter = new StringWriter();
                copier.copy(jsonXmlDriver.createReader(new StringReader(resp)),
                        new PrettyPrintWriter(strWriter));
                resp = strWriter.toString();
                System.out.println(resp);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
    return resp;
}

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

public void enableWebSudo() {
    final HttpClient httpClient = prepareClient();
    final PostMethod method = new PostMethod(getWebSudoUrl());

    final String token = DigestUtils
            .shaHex(String.valueOf(System.currentTimeMillis() + String.valueOf(Math.random())));
    sharedVariables.setWebSudoToken(token);

    try {/*from w w  w  .  j  av a  2s.  co m*/
        method.setParameter("webSudoToken", token);

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