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.dianping.lion.service.impl.HttpMailServiceImpl.java

public boolean sendMail(int mailType, String mail, String title, String body)
        throws UnsupportedEncodingException {
    String result = null;//  w  ww . j  a v  a  2  s .co m
    StringBuffer mailUrl = new StringBuffer(path);
    StringBuffer mailPara = new StringBuffer();
    mailPara.append("{type:").append(mailType).append(",to:").append(mail).append(",pair:{title:").append(title)
            .append(",body:").append(body).append("}}");
    method = new PostMethod(mailUrl.toString());
    method.addParameter("jsonm", mailPara.toString());
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    try {
        httpClient.executeMethod(method);
        result = method.getResponseBodyAsString();
    } catch (Exception e) {
        logger.error(e);
        return false;
    }
    if (result.contains("200")) {
        return true;
    }
    return false;
}

From source file:com.testmax.util.HttpUtil.java

public String postRequest(String url, String param, String xml) {

    String resp = "";

    PostMethod post = new PostMethod(url);

    if (param.equalsIgnoreCase("body")) {
        //xmlData=urlConf.getUrlParamValue(param);
        byte buf[] = xml.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(buf);
        post.setRequestEntity(new InputStreamRequestEntity(new BufferedInputStream(in), xml.length()));

    } else {//from   w w  w. j a  va 2  s.  c o  m
        post.setRequestHeader(param, xml);
    }
    post.setRequestHeader("Content-type", "text/xml; charset=utf-8");
    // Get HTTP client
    org.apache.commons.httpclient.HttpClient httpsclient = new org.apache.commons.httpclient.HttpClient();

    // Execute request
    try {

        int response = -1;

        try {
            response = httpsclient.executeMethod(post);
            resp = post.getResponseBodyAsString();
            Header[] heads = post.getResponseHeaders();

            String header = "";
            for (Header head : heads) {
                header += head.getName() + ":" + head.getValue();
            }
            System.out.println("Header=" + header);
            WmLog.printMessage("Response: " + resp);
            WmLog.printMessage("Response Header: " + header);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException 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:ca.uvic.cs.tagsea.monitor.NetworkLogging.java

public synchronized boolean uploadForDate(Date d) throws IOException {
    File f = SimpleDayLog.findLogFileForDay(d);
    if (f.length() == 0)
        return true;

    PostMethod post = new PostMethod(uploadScript);
    Display disp = TagSEAMonitorPlugin.getDefault().getWorkbench().getDisplay();
    int id = getUID();
    if (id < 0) {
        //error getting the user id. Quit.
        return false;
    }//from www .  ja va 2 s.c o m
    Part[] parts = { new StringPart("KIND", "log"), new FilePart("MYLAR" + id, f.getName(), f) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(post);
    resp = getData(post.getResponseBodyAsStream());
    if (status != 200) {
        disp.syncExec(new Runnable() {
            public void run() {
                MessageDialog.openError(null, "Error Sending File", resp);
            }
        });
        return false;

    }
    MonitorPreferences.setLastSendDate(d);
    return true;

}

From source file:com.khipu.lib.java.KhipuService.java

protected String post(Map data) throws KhipuJSONException, IOException {

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Khipu.API_URL + getMethodEndpoint());
    NameValuePair[] params = new NameValuePair[data.keySet().size()];

    int i = 0;/*www .j  av  a  2s  .c  o m*/
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); i++) {
        String key = (String) iterator.next();
        params[i] = new NameValuePair(key, (String) data.get(key));
    }

    postMethod.setRequestBody(params);

    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (client.executeMethod(postMethod) == HttpStatus.SC_OK) {
        InputStream stream = postMethod.getResponseBodyAsStream();
        String contentAsString = getContentAsString(stream);
        stream.close();
        postMethod.releaseConnection();
        return contentAsString;
    }
    InputStream stream = postMethod.getResponseBodyAsStream();
    String contentAsString = getContentAsString(stream);
    stream.close();
    postMethod.releaseConnection();
    throw new KhipuJSONException(contentAsString);
}

From source file:be.fedict.eid.pkira.xkmsws.util.HttpUtil.java

public byte[] postMessage(String message) throws XKMSClientException {
    try {/*  ww  w.  j av a 2  s . c o  m*/
        PostMethod method = new PostMethod(endpointAddress);
        method.setRequestEntity(new StringRequestEntity(message, "text/xml", "utf-8"));
        int resultCode = client.executeMethod(method);
        if (resultCode != 200) {
            throw new XKMSClientException("Error calling XKMS service. Got back status code " + resultCode);
        }

        return method.getResponseBody();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e); // shouldn't happen
    } catch (HttpException e) {
        throw new XKMSClientException("Error calling XKMS service.", e);
    } catch (IOException e) {
        throw new XKMSClientException("Error calling XKMS service.", e);
    }
}

From source file:eu.seaclouds.platform.planner.optimizerTest.discovererOutput.DiscovererOutputTest.java

@Test(enabled = false)
public void testPresenceHeartbeat() {
    log.info("=== TEST for RETRIEVING DATA FROM DISCOVERER  STARTED ===");

    String url = null;// w  w w.j ava 2  s. c  o m

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.addParameter("oid", "2775488370683472268");

    executeAndCheck(client, method);

    log.info("=== TEST for RETRIEVING DATA FROM DISCOVERER  FINISEHD ===");
}

From source file:net.sf.j2ep.requesthandlers.EntityEnclosingRequestHandler.java

/**
 * Will set the input stream and the Content-Type header to match this request.
 * Will also set the other headers send in the request.
 * //from  w w w . j av  a 2s.  c o  m
 * @throws IOException An exception is throws when there is a problem getting the input stream
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {

    EntityEnclosingMethod method = null;

    if (request.getMethod().equalsIgnoreCase("POST")) {
        method = new PostMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("PUT")) {
        method = new PutMethod(url);
    }

    setHeaders(method, request);

    InputStreamRequestEntity stream;
    stream = new InputStreamRequestEntity(request.getInputStream());
    method.setRequestEntity(stream);
    method.setRequestHeader("Content-type", request.getContentType());

    return method;

}

From source file:com.zb.app.biz.service.WeixinTest.java

public void login() {
    httpClient = new HttpClient();
    PostMethod post = new PostMethod(loginUrl);
    post.addParameter(new NameValuePair("username", account));
    post.addParameter(new NameValuePair("pwd", DigestUtils.md5Hex(password)));
    post.addParameter(new NameValuePair("imgcode", ""));
    post.addParameter(new NameValuePair("f", "json"));
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");

    try {//  w w  w.j a  v a 2s .co m
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String res = post.getResponseBodyAsString();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(res);
            JSONObject _obj = (JSONObject) obj.get("base_resp");
            @SuppressWarnings("unused")
            String msg = (String) _obj.get("err_msg");
            String redirect_url = (String) obj.get("redirect_url");
            Long errCode = (Long) _obj.get("ret");
            if (0 == errCode) {
                isLogin = true;
                token = StringUtils.substringAfter(redirect_url, "token=");
                if (null == token) {
                    token = StringUtils.substringBetween(redirect_url, "token=", "&");
                }
                StringBuffer cookie = new StringBuffer();
                for (Cookie c : httpClient.getState().getCookies()) {
                    cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
                this.cookiestr = cookie.toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.predic8.membrane.core.interceptor.cbr.XPathCBRInterceptorIntegrationTest.java

private PostMethod createPostMethod() {
    PostMethod post = new PostMethod("http://localhost:3024/");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/cbr/order.xml")));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");
    return post;// w ww  .  j a va 2s.c o  m
}

From source file:com.cloud.ucs.manager.UcsHttpClient.java

public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    //post.setFollowRedirects(true);
    try {/*from w  ww .jav a  2s  .  co  m*/
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}