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

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

Introduction

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

Prototype

public void addParameters(NameValuePair[] paramArrayOfNameValuePair) 

Source Link

Usage

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

PostMethod getPOSTMethod(String servicePath, List<WebscriptParam> params) {
    PostMethod postMethod = new PostMethod(this.baseUrl + servicePath);

    if (params != null) {
        List<NameValuePair> args = new ArrayList<NameValuePair>();
        for (WebscriptParam param : params) {
            args.add(new NameValuePair(param.getName(), param.getValue()));
        }/* w  w  w  .  j  av a2s .  c  o m*/
        postMethod.addParameters(args.toArray(new NameValuePair[args.size()]));
    }
    return postMethod;
}

From source file:org.apache.nutch.protocol.httpclient.HttpFormAuthentication.java

private void sendPost(String url, List<NameValuePair> params) throws Exception {
    PostMethod post = null;
    try {// w ww .  j a v  a  2  s.  c o m
        if (authConfigurer.isLoginRedirect()) {
            post = new PostMethod(url) {
                @Override
                public boolean getFollowRedirects() {
                    return true;
                }
            };
        } else {
            post = new PostMethod(url);
        }
        // we can't use post.setFollowRedirects(true) as it will throw
        // IllegalArgumentException:
        // Entity enclosing requests cannot be redirected without user
        // intervention
        setLoginHeader(post);

        // NUTCH-2280
        LOG.debug("FormAuth: set cookie policy");
        this.setCookieParams(authConfigurer, post.getParams());

        post.addParameters(params.toArray(new NameValuePair[0]));
        int rspCode = client.executeMethod(post);
        if (LOG.isDebugEnabled()) {
            LOG.debug("rspCode: " + rspCode);
            LOG.debug("\nSending 'POST' request to URL : " + url);

            LOG.debug("Post parameters : " + params);
            LOG.debug("Response Code : " + rspCode);
            for (Header header : post.getRequestHeaders()) {
                LOG.debug("Response headers : " + header);
            }
        }
        String rst = IOUtils.toString(post.getResponseBodyAsStream());
        LOG.debug("login post result: " + rst);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.apache.nutch.protocol.httpclient.proxy.HttpFormAuthentication.java

private void sendPost(String url, List<NameValuePair> params) throws Exception {
    PostMethod post = null;
    try {/*from  w ww . j a  v a  2s  .com*/
        if (authConfigurer.isLoginRedirect()) {
            post = new PostMethod(url) {
                @Override
                public boolean getFollowRedirects() {
                    return true;
                }
            };
        } else {
            post = new PostMethod(url);
        }
        // we can't use post.setFollowRedirects(true) as it will throw
        // IllegalArgumentException:
        // Entity enclosing requests cannot be redirected without user
        // intervention
        setLoginHeader(post);
        post.addParameters(params.toArray(new NameValuePair[0]));
        int rspCode = client.executeMethod(post);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("rspCode: " + rspCode);
            LOGGER.debug("\nSending 'POST' request to URL : " + url);

            LOGGER.debug("Post parameters : " + params);
            LOGGER.debug("Response Code : " + rspCode);
            for (Header header : post.getRequestHeaders()) {
                LOGGER.debug("Response headers : " + header);
            }
        }
        String rst = IOUtils.toString(post.getResponseBodyAsStream());
        LOGGER.debug("login post result: " + rst);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.apache.wookie.proxy.ProxyClient.java

public String post(String uri, String xmlData, Configuration properties) throws Exception {
    fLogger.debug("POST to " + uri); //$NON-NLS-1$
    PostMethod method = new PostMethod(uri);
    method.setDoAuthentication(true);/*from ww  w.ja va  2 s .  c  o m*/

    if (this.parameters.length > 0) {
        method.addParameters(this.parameters);
    } else {
        method.setRequestEntity(new StringRequestEntity(xmlData, "text/xml", "UTF8"));//$NON-NLS-1$  //$NON-NLS-2$
    }

    return executeMethod(method, properties);
}

From source file:org.cauldron.tasks.HttpCall.java

/**
 * Running an HttpTask retrieves the path contents according to the task
 * attributes. POST body comes from the input.
 *//* w  w  w. j  a va2 s. c  om*/

public Object run(Context context, Object input) throws TaskException {
    // For POST, body must be available as input.

    String body = null;
    if (!isGet) {
        body = (String) context.convert(input, String.class);
        if (body == null)
            throw new TaskException("HTTP POST input must be convertible to String");
    }

    // Prepare request parameters.

    NameValuePair[] nvp = null;
    if (params != null && params.size() > 0) {
        nvp = new NameValuePair[params.size()];
        int count = 0;

        for (Iterator entries = params.entrySet().iterator(); entries.hasNext();) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            nvp[count++] = new NameValuePair(key, value);
        }
    }

    // Create the retrieval method and set parameters.
    //

    HttpMethod method;
    if (isGet) {
        GetMethod get = new GetMethod();
        if (nvp != null)
            get.setQueryString(nvp);
        method = get;
    } else {
        PostMethod post = new PostMethod();
        post.setRequestBody(body);
        if (nvp != null)
            post.addParameters(nvp);
        method = post;
    }

    // Make the call.

    method.setPath(path);
    HttpConnection connection = connectionManager.getConnection(config);

    try {
        connection.open();
        method.execute(new HttpState(), connection);
        return method.getResponseBodyAsString();
    } catch (HttpException e) {
        throw new TaskException(e);
    } catch (IOException e) {
        throw new TaskException(e);
    } finally {
        connection.close();
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Gets the authentication method.//from  ww  w . j a v a2 s .  c  o  m
 * 
 * @param auth
 *          the HTML form authentication
 * 
 * @return the authentication method
 */
private HttpMethodBase getAuthenticationMethod(HtmlFormAuthentication auth) {
    HttpMethodBase authenticationMethod = null;
    if (auth.getHttpMethod().equals(HttpMethod.POST)) {
        final PostMethod postMethod = new PostMethod((auth.getLoginUri()));

        final NameValuePair[] postData = new NameValuePair[auth.getFormItems().size()];
        int i = 0;
        for (String key : auth.getFormItems().keySet()) {
            postData[i] = new NameValuePair(key, auth.getFormItems().get(key));
            i++;
        }
        postMethod.addParameters(postData);
        authenticationMethod = postMethod;
    } else if (auth.getHttpMethod().equals(HttpMethod.GET)) {
        final String requestString = RequestUtil.appendParams(auth.getLoginUri(), auth.getFormItems());
        LOG.debug("GET request string for authentication: " + requestString);
        final GetMethod getMethod = new GetMethod(requestString);
        authenticationMethod = getMethod;
    }

    return authenticationMethod;
}

From source file:org.exist.debugger.HttpSession.java

public void run() {
    HttpClient client = new HttpClient();

    PostMethod method = new PostMethod(url);

    NameValuePair[] postData = new NameValuePair[1];
    postData[0] = new NameValuePair("XDEBUG_SESSION", "default");

    method.addParameters(postData);

    try {/*from ww  w .  j av  a2 s .  c o m*/
        System.out.println("sending http request with debugging flag");

        debugger.terminate(url, client.executeMethod(method));

        System.out.println("get http response");
    } catch (Exception e) {
    }
}

From source file:org.frameworkset.spi.remote.http.HttpReqeust.java

/**
 * post/*w  w w  . j  av a  2s  .  c o m*/
 * 
 * @param url
 * @param params
 * @param files
 * @throws AppException
 */
public static String httpPostforString(String url, String cookie, String userAgent, Map<String, Object> params,
        Map<String, File> files) throws Exception {
    // System.out.println("post_url==> "+url);
    // String cookie = getCookie(appContext);
    // String userAgent = getUserAgent(appContext);

    HttpClient httpClient = null;
    PostMethod httpPost = null;
    Part[] parts = null;
    NameValuePair[] paramPair = null;
    if (files != null) {
        // post???
        int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size());
        parts = new Part[length];
        int i = 0;
        if (params != null) {
            Iterator<Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, Object> entry = it.next();
                parts[i++] = new StringPart(entry.getKey(), String.valueOf(entry.getValue()), UTF_8);
                // System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
            }
        }
        if (files != null) {
            Iterator<Entry<String, File>> it = files.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, File> entry = it.next();
                try {
                    parts[i++] = new FilePart(entry.getKey(), entry.getValue());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // System.out.println("post_key_file==> "+file);
            }
        }
    } else if (params != null && params.size() > 0) {
        paramPair = new NameValuePair[params.size()];
        Iterator<Entry<String, Object>> it = params.entrySet().iterator();
        NameValuePair paramPair_ = null;
        for (int i = 0; it.hasNext(); i++) {
            Entry<String, Object> entry = it.next();
            paramPair_ = new NameValuePair();
            paramPair_.setName(entry.getKey());
            paramPair_.setValue(String.valueOf(entry.getValue()));
            paramPair[i] = paramPair_;
        }
    }

    String responseBody = "";
    int time = 0;
    do {
        try {
            httpClient = getHttpClient();
            httpPost = getHttpPost(url, cookie, userAgent);
            if (files != null) {
                httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams()));
            } else {
                httpPost.addParameters(paramPair);

            }

            int statusCode = httpClient.executeMethod(httpPost);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpRuntimeException("" + statusCode);
            } else if (statusCode == HttpStatus.SC_OK) {
                Cookie[] cookies = httpClient.getState().getCookies();
                String tmpcookies = "";
                for (Cookie ck : cookies) {
                    tmpcookies += ck.toString() + ";";
                }
                // //?cookie
                // if(appContext != null && tmpcookies != ""){
                // appContext.setProperty("cookie", tmpcookies);
                // appCookie = tmpcookies;
                // }
            }
            responseBody = httpPost.getResponseBodyAsString();
            // System.out.println("XMLDATA=====>"+responseBody);
            break;
        } catch (HttpException e) {
            time++;
            if (time < RETRY_TIME) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                }
                continue;
            }
            // ?????
            throw new HttpRuntimeException("", e);
        } catch (IOException e) {
            time++;
            if (time < RETRY_TIME) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                }
                continue;
            }
            // ?
            throw new HttpRuntimeException("", e);
        } finally {
            // 
            httpPost.releaseConnection();
            httpClient = null;
        }
    } while (time < RETRY_TIME);
    return responseBody;
    // responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
    // if(responseBody.contains("result") &&
    // responseBody.contains("errorCode") &&
    // appContext.containsProperty("user.uid")){
    // try {
    // Result res = Result.parse(new
    // ByteArrayInputStream(responseBody.getBytes()));
    // if(res.getErrorCode() == 0){
    // appContext.Logout();
    // appContext.getUnLoginHandler().sendEmptyMessage(1);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // return new ByteArrayInputStream(responseBody.getBytes());
}

From source file:org.iottly.openfire.plugin.HTTPPoster.java

public int postTo(String targetUrl, Map<String, Object> parameters) {
    Log.debug("Do the post for " + parameters.get("msg"));
    PostMethod post = new PostMethod(targetUrl);

    int statusCode = -1;
    post.addParameters(mapToPairsList(parameters));
    try {/*w  ww. ja  va 2s  . co m*/
        statusCode = client.executeMethod(post);
    } catch (Exception e) {
        Log.debug("Something went wrong in the HTTP post:" + e.getMessage());
    } finally {
        post.releaseConnection();
    }
    return statusCode;
}

From source file:org.mskcc.pathdb.action.web_api.NeighborhoodMapRetriever.java

/**
 * Gets url to neighborhood map server.//ww w.  j av a 2  s  .c o m
 *
 * @param biopaxAssembly XmlAssemby
 * @return ImageIcon
 * @throws Exception
 */
private ImageIcon getNeighborhoodMapImage(XmlAssembly biopaxAssembly) throws Exception {

    log.info("NeighborhoodMapRetriever.getNeighborhoodMapImage()");

    HttpClient client = new HttpClient();
    NameValuePair nvps[] = new NameValuePair[6];
    nvps[0] = new NameValuePair("data", biopaxAssembly.getXmlString());
    nvps[1] = new NameValuePair("width", Integer.toString(WIDTH));
    nvps[2] = new NameValuePair("height", Integer.toString(HEIGHT));
    nvps[3] = new NameValuePair("unwanted_interactions", UNWANTED_INTERACTIONS_STRING.trim());
    nvps[4] = new NameValuePair("unwanted_small_molecules", UNWANTED_SMALL_MOLECULES_STRING.trim());
    nvps[5] = new NameValuePair("version", "1.0");
    PostMethod method = new PostMethod(CPathUIConfig.getWebUIBean().getImageMapServerURL());
    method.setRequestHeader("Accept", "text/*,image");
    method.addParameters(nvps);

    // execute method
    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
    try {
        log.info("NeighborhoodMapRetriever.getNeighborhoodMapImage(), executing method....");
        int statusCode = client.executeMethod(method);
        log.info(
                "NeighborhoodMapRetriever.getNeighborhoodMapImage(), neighborhood map image fetched, response code: "
                        + Integer.toString(statusCode) + ",  reading response...");
        if (statusCode != HttpStatus.SC_OK) {
            throw new Exception("Error fetching neighborhood map image: " + method.getStatusLine());
        }
        // get content
        InputStream instream = method.getResponseBodyAsStream();
        byte[] buffer = new byte[4096];
        int len;
        int totalBytes = 0;
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        instream.close();
    } finally {
        // release current connection
        method.releaseConnection();
    }

    // outta here
    byte[] responseBody = outstream.toByteArray();
    return (responseBody != null) ? new ImageIcon(responseBody) : null;
}