Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:eu.eco2clouds.scheduler.em.EMClientHC.java

private String postMethod(String url, String payload, String contentType, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    //setHeaders(method, contentType);
    setHeaders(method, Configuration.bonfireApiGroup);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {//w ww.  ja va2 s  . c om
        RequestEntity requestEntity = new StringRequestEntity(payload, contentType, null);
        method.setRequestEntity(requestEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... 
            logger.warn(
                    "post managed experiments information... : " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:gsn.vsensor.DataCleanVirtualSensor.java

public boolean httpPost(String url, String xmlString) {

    boolean success = true;
    PostMethod post = new PostMethod(url);
    RequestEntity entity;/*from  w  ww .  j a va  2 s  . c o m*/
    HttpClient httpclient = new HttpClient();

    if (metadata_server_requieres_password) {
        httpclient.getState().setCredentials(new AuthScope(metadata_server_url, 80),
                new UsernamePasswordCredentials(username, password));
    }

    try {
        entity = new StringRequestEntity(xmlString, "text/xml", "ISO-8859-1");

        post.setRequestEntity(entity);
        int result = httpclient.executeMethod(post);

        if (result != NORMAL_RESULT) {
            logger.warn("Response status code: " + result);

            // Display response
            logger.warn("Response body: ");
            logger.warn(post.getResponseBodyAsString());
            success = false;
        }
    }

    catch (UnsupportedEncodingException e) {
        logger.warn(new StringBuilder("Unsupported encoding for: ").append(url).toString());
        success = false;
    }

    catch (HttpException e) {
        logger.warn(new StringBuilder("Error for: ").append(url).append(e).toString());
        success = false;
    }

    catch (IOException e) {
        logger.warn(new StringBuilder("Error for: ").append(url).append(e).toString());
        success = false;
    }

    finally {
        post.releaseConnection();
    }

    return success;
}

From source file:de.michaeltamm.W3cMarkupValidator.java

/**
 * Validates the given <code>html</code>.
 *
 * @param html a complete HTML document//from   w  ww.  j a va2 s.c  o m
 */
public W3cMarkupValidationResult validate(String html) {
    if (_httpClient == null) {
        final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        _httpClient = new HttpClient(connectionManager);
    }
    final PostMethod postMethod = new PostMethod(_checkUrl);
    final Part[] data = {
            // The HTML to validate ...
            new StringPart("fragment", html, "UTF-8"), new StringPart("prefill", "0", "UTF-8"),
            new StringPart("doctype", "Inline", "UTF-8"), new StringPart("prefill_doctype", "html401", "UTF-8"),
            // List Messages Sequentially | Group Error Messages by Type ...
            new StringPart("group", "0", "UTF-8"),
            // Show source ...
            new StringPart("ss", "1", "UTF-8"),
            // Verbose Output ...
            new StringPart("verbose", "1", "UTF-8"), };
    postMethod.setRequestEntity(new MultipartRequestEntity(data, postMethod.getParams()));
    try {
        final int status = _httpClient.executeMethod(postMethod);
        if (status != 200) {
            throw new RuntimeException(_checkUrl + " responded with " + status);
        }
        final String pathPrefix = _checkUrl.substring(0, _checkUrl.lastIndexOf('/') + 1);
        final String resultPage = getResponseBody(postMethod).replace("\"./", "\"" + pathPrefix)
                .replace("src=\"images/", "src=\"" + pathPrefix + "images/")
                .replace("<script type=\"text/javascript\" src=\"loadexplanation.js\">",
                        "<script type=\"text/javascript\" src=\"" + pathPrefix + "loadexplanation.js\">");
        return new W3cMarkupValidationResult(resultPage);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:ccc.api.http.SiteBrowserImpl.java

/** {@inheritDoc} */
@Override//from   ww  w. j a v  a2 s  .  c o m
public String postUrlEncoded(final ResourceSummary rs, final Map<String, String[]> params) {
    /* This method deliberately elides charset values to replicate the
     * behaviour of a typical browser.                                    */

    final PostMethod post = new PostMethod(_hostUrl + rs.getAbsolutePath());
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    final List<NameValuePair> qParams = new ArrayList<NameValuePair>();
    for (final Map.Entry<String, String[]> param : params.entrySet()) {
        for (final String value : param.getValue()) {
            final NameValuePair qParam = new NameValuePair(param.getKey(), value);
            qParams.add(qParam);
        }
    }

    final StringBuilder buffer = createQueryString(qParams);
    post.setRequestEntity(new StringRequestEntity(buffer.toString()));

    return invoke(post);
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public CreateAccountResult createAccount(CreateAccountRequest request) {
    log.info("Create account request:" + request);
    PostMethod method = null;
    try {//from   w  ww.j  a  va  2  s  .c  o m
        method = new PostMethod(baseUrl + ACCOUNTS);
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, CreateAccountResult.class);

        } else {
            throw new RuntimeException("Failed to create account, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        log.error("Failed to create account", e);
        throw new RuntimeException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.founder.zykc.controller.FdbzcrjryController.java

@RestfulAnnotation(serverId = "3")
@RequestMapping(value = "/queryFdbzcrjList", method = RequestMethod.POST)
public @ResponseBody EasyUIPage queryList(EasyUIPage page,
        @RequestParam(value = "rows", required = false) Integer rows, String sfzhm, String zwxm,
        SessionBean sessionBean) {/*from   w  w w.j  a  va2  s.c  o m*/

    page.setPagePara(rows);

    String url = "http://10.78.17.154:9999/lbs";
    String urlParameter = "operation=ForbiddenDepartureManagement_GetInfoByIDName_v001&license=a756244eb0236bdc26061cb6b6bdb481&content=";

    int total = 0;
    List<FdbzcrjryVo> list = new ArrayList<FdbzcrjryVo>();

    String content = "";
    boolean isUpdated = false;
    if (!StringUtils.isEmpty(sfzhm) && !StringUtils.isEmpty(zwxm)) {

        content = "{\"data\":[{\"SFZHM\":\"" + sfzhm + "\"," + "\"ZWXM\":\"" + zwxm + "\"}]," + "\"pageindex\":"
                + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}";
    } else if (StringUtils.isEmpty(sfzhm)) {
        content = "{\"data\":[{\"ZWXM\":\"" + zwxm + "\"}]," + "\"pageindex\":"
                + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}";
    } else if (StringUtils.isEmpty(zwxm)) {
        // content = "{\"data\":[{\"SFZHM\":\"" + sfzhm
        // + "\"}]}";
        content = "{\"data\":[{\"SFZHM\":\"" + sfzhm + "\"}]," + "\"pageindex\":"
                + (Integer.valueOf(page.getPage()) - 1) + "," + "\"pagesize\":" + rows + "}";
    }

    try {
        content = urlParameter + java.net.URLEncoder.encode(content, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    PostMethod postMethod = new PostMethod(url);
    byte[] b;
    try {
        b = content.getBytes("utf-8");

        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(50000);

    int statusCode = 0;
    try {
        statusCode = httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (statusCode == 200) {
        String soapResponseData = "";
        try {
            soapResponseData = postMethod.getResponseBodyAsString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jb = JSONObject.fromObject(soapResponseData);

        if ((Integer) jb.get("datalen") > 0) {

            Map<String, String> dictHkszd = new HashMap<String, String>();//?
            Map<String, String> dictFlyj = new HashMap<String, String>();//??
            Map<String, String> dictCsd = new HashMap<String, String>();//
            Map<String, String> dictBbrylx = new HashMap<String, String>();//
            Map<String, String> dictPcs = new HashMap<String, String>();//
            Map<String, String> dictXb = new HashMap<String, String>();//
            Map<String, String> dictZjzl = new HashMap<String, String>();//??   
            Map<String, String> dictZzjg = new HashMap<String, String>();//      
            Map<String, String> dictMj = new HashMap<String, String>();//

            try {
                dictHkszd = sysDictGlService.getDictMap("BD_D_FDBZCJHKSZD");
                dictFlyj = sysDictGlService.getDictMap("BD_D_FDBZCJFLYJ");
                dictCsd = sysDictGlService.getDictMap("BD_D_FDBZCJCSD");
                dictBbrylx = sysDictGlService.getDictMap("BD_D_FDBZCJBBRYLB");
                dictPcs = sysDictGlService.getDictMap("BD_D_FDBZCJPCS");
                dictXb = sysDictGlService.getDictMap("BD_D_FDBZCJXB");
                dictZjzl = sysDictGlService.getDictMap("BD_D_FDBZCJZJZL");
                dictZzjg = sysDictGlService.getDictMap("BD_D_FDBZCJORG");
                dictMj = sysDictGlService.getDictMap("BD_D_FDBZCJMJ");

            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            total = Integer.valueOf(jb.getString("total"));

            for (int i = 0; i < (Integer) jb.get("datalen"); i++) {
                JSONObject jo = jb.getJSONArray("data").getJSONObject(i);

                FdbzcrjryVo vo = new FdbzcrjryVo();
                if (jo.containsKey("BBDWBM")) {
                    vo.setBbdwbm(dictZzjg.get(jo.getString("BBDWBM")));
                }
                if (jo.containsKey("BBLXDH")) {
                    vo.setBblxdh(jo.getString("BBLXDH"));
                }
                if (jo.containsKey("BBLXR")) {
                    vo.setBblxr(jo.getString("BBLXR"));
                }
                if (jo.containsKey("BBQX")) {
                    vo.setBbqx(jo.getString("BBQX"));
                }
                if (jo.containsKey("BBRQ")) {
                    vo.setBbrq(jo.getString("BBRQ"));
                }
                if (jo.containsKey("BBRYLB")) {
                    vo.setBbrylb(dictBbrylx.get(jo.getString("BBRYLB")));
                }
                if (jo.containsKey("BBYY")) {
                    vo.setBbyy(jo.getString("BBYY"));
                }
                if (jo.containsKey("BZ")) {
                    vo.setBz(jo.getString("BZ"));
                }
                if (jo.containsKey("CSD")) {
                    vo.setCsd(dictCsd.get(jo.getString("CSD")));
                }
                if (jo.containsKey("DAH")) {
                    vo.setDah(jo.getString("DAH"));
                }
                if (jo.containsKey("DWDH")) {
                    vo.setDwdh(jo.getString("DWDH"));
                }
                if (jo.containsKey("FLYJ")) {
                    vo.setFlyj(dictFlyj.get(jo.getString("FLYJ")));
                }
                if (jo.containsKey("GZDW")) {
                    vo.setGzdw(jo.getString("GZDW"));
                }
                if (jo.containsKey("HKSZD")) {
                    vo.setHkszd(dictHkszd.get(jo.getString("HKSZD")));
                }
                if (jo.containsKey("FLYJ")) {
                    vo.setFlyj(dictFlyj.get(jo.getString("FLYJ")));
                }
                if (jo.containsKey("JTDH")) {
                    vo.setJtdh(jo.getString("JTDH"));
                }
                if (jo.containsKey("MJ")) {
                    vo.setMj(dictMj.get(jo.getString("MJ")));
                }
                if (jo.containsKey("PCSSZD")) {
                    vo.setPcsszd(dictPcs.get(jo.getString("PCSSZD")));
                }
                if (jo.containsKey("PYXM")) {
                    vo.setPyxm(jo.getString("PYXM"));
                }
                if (jo.containsKey("SFZDCK")) {
                    vo.setSfzdck(jo.getString("SFZDCK"));
                }
                if (jo.containsKey("SFZHM")) {
                    vo.setSfzhm(jo.getString("SFZHM"));
                }
                if (jo.containsKey("XB")) {
                    vo.setXb(dictXb.get(jo.getString("XB")));
                }
                if (jo.containsKey("XZZ")) {
                    vo.setXzz(jo.getString("XZZ"));
                }
                if (jo.containsKey("ZJHM")) {
                    vo.setZjhm(jo.getString("ZJHM"));
                }
                if (jo.containsKey("ZJZL")) {
                    vo.setZjzl(dictZjzl.get(jo.getString("ZJZL")));
                }
                if (jo.containsKey("ZWM")) {
                    vo.setZwm(jo.getString("ZWM"));
                }
                if (jo.containsKey("ZWX")) {
                    vo.setZwx(jo.getString("ZWX"));
                }
                if (jo.containsKey("RYDH")) {
                    vo.setRydh(jo.getString("RYDH"));
                }
                list.add(vo);
            }
        }
    } else {
        System.out.println("????" + statusCode);
    }
    page.setRows(list);
    page.setTotal(total);
    return page;
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

public static void populateCSE(String authtoken, String domain, double score) {

    try {//from   w  w w. j ava 2s  .c o m
        HttpClient client = new HttpClient();
        PostMethod annotation_post = new PostMethod("http://www.google.com/coop/api/default/annotations/");

        String label;
        domain = URLEncoder.encode(domain, "UTF-8");
        if (domain.indexOf("http") < 0)
            label = "<Annotation about=\"http://" + domain + "/*\" score=\"" + score + "\">";
        else
            label = "<Annotation about=\"" + domain + "/*\" score=\"" + score + "\">";
        String new_annotation = "<Batch>" + "<Add>" + "<Annotations>" + label
                + "<Label name=\"_cse_testengine\"/>" + "</Annotation>" + "</Annotations>" + "</Add>"
                + "</Batch>";

        System.out.println("uploading annotation :" + new_annotation);
        annotation_post.addRequestHeader("Content-type", "text/xml");
        annotation_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

        StringRequestEntity rq_en = new StringRequestEntity(new_annotation, "text/xml", "UTF-8");
        annotation_post.setRequestEntity(rq_en);

        int astatusCode = client.executeMethod(annotation_post);

        if (astatusCode == HttpStatus.SC_OK) {
            System.out.println("Annotations updated");
            //indexurlcount++;
        } else {
            System.out.println("Annotation update failed");
            String responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
            System.out.println("Result remoteRequest: " + responseBody);
            System.out.println("Annotation update failed");
            //rejectedurlcount++;
        }
    } catch (Exception e) {
        System.out.println("\nexception:" + e.getMessage());
    }
}

From source file:de.ingrid.iplug.dsc.utils.BwstrLocUtil.java

/**
 * Get the response from BwStrLoc using Referencesystem 4326 and distance 0.
 * //from www . ja v  a  2  s  .  c o m
 * @param bwStrId
 * @param kmFrom
 * @param kmTo
 * @return
 */
public String getResponse(String bwStrId, String kmFrom, String kmTo) {
    String response = null;

    PostMethod post = new PostMethod(bwstrLocEndpoint);
    post.setParameter("Content-Type", "application/json");

    try {
        RequestEntity reqE = new StringRequestEntity(
                "{\"queries\":[{\"qid\":1,\"bwastrid\":\"" + bwStrId + "\",\"stationierung\":{\"km_von\":"
                        + kmFrom + ",\"km_bis\":" + kmTo
                        + ",\"offset\":0},\"spatialReference\":{\"wkid\":4326}}]}",
                "application/json", "UTF-8");
        post.setRequestEntity(reqE);
        int resp = getHttpClient().executeMethod(post);
        if (resp != 200) {
            throw new Exception("Invalid HTTP Response Code.: " + resp);
        }
        response = post.getResponseBodyAsString();
    } catch (Exception e) {
        log.error("Error getting response from BwStrLocator at: " + bwstrLocEndpoint);
    } finally {
        post.releaseConnection();
    }
    return response;
}

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

@SuppressWarnings("deprecation")
public Boolean revokeGrantFromUserGroup() {
    String userGroupID = Util.input("Enter UserGroupID where you want to revoke a grant:");
    String grantID = Util.input("Enter GrantID to remove the grant in the UserGroup: ");
    // String userGroupID = "escidoc:27004";
    // String grantID = "escidoc:27011";
    Document userGroupXML = this.getUserGroupXML(userGroupID);
    if (userGroupXML == null) {
        return false;
    }/* w w  w  .  ja v a2s .c om*/
    Element rootElement = userGroupXML.getRootElement();
    String lastModificationDate = rootElement.getAttributeValue("last-modification-date");
    System.out.println("lastModificationDate: " + lastModificationDate);
    if (this.USER_HANDLE != null) {
        PostMethod post = new PostMethod(this.FRAMEWORK_URL + "/aa/user-group/" + userGroupID
                + "/resources/grants/grant/" + grantID + "/revoke-grant");
        post.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            post.setRequestEntity(new StringRequestEntity(
                    Util.getParamXml(Util.OPTION_REMOVE_SELECTOR, lastModificationDate, grantID)));
            this.client.executeMethod(post);
            if (post.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + post.getStatusCode());
                return false;
            }
            System.out.println("Grant " + grantID + " revoked from " + userGroupID);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in revokeGrantFromUserGroup: No userHandle available");
    }
    return true;
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.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));//  ww w  . j av a2s . c om

    method.releaseConnection();
}