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

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

Introduction

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

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:com.synox.android.operations.OAuth2GetAccessToken.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    PostMethod postMethod = null;

    try {/*w  w  w.j  a v  a  2 s .c  o  m*/
        parseAuthorizationResponse();
        if (mOAuth2ParsedAuthorizationResponse.keySet().contains(OAuth2Constants.KEY_ERROR)) {
            if (OAuth2Constants.VALUE_ERROR_ACCESS_DENIED
                    .equals(mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_ERROR))) {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR_ACCESS_DENIED);
            } else {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
            }
        }

        if (result == null) {
            NameValuePair[] nameValuePairs = new NameValuePair[4];
            nameValuePairs[0] = new NameValuePair(OAuth2Constants.KEY_GRANT_TYPE, mGrantType);
            nameValuePairs[1] = new NameValuePair(OAuth2Constants.KEY_CODE,
                    mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_CODE));
            nameValuePairs[2] = new NameValuePair(OAuth2Constants.KEY_REDIRECT_URI, mRedirectUri);
            nameValuePairs[3] = new NameValuePair(OAuth2Constants.KEY_CLIENT_ID, mClientId);
            //nameValuePairs[4] = new NameValuePair(OAuth2Constants.KEY_SCOPE, mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_SCOPE));         

            postMethod = new PostMethod(client.getWebdavUri().toString());
            postMethod.setRequestBody(nameValuePairs);
            int status = client.executeMethod(postMethod);

            String response = postMethod.getResponseBodyAsString();
            if (response != null && response.length() > 0) {
                JSONObject tokenJson = new JSONObject(response);
                parseAccessTokenResult(tokenJson);
                if (mResultTokenMap.get(OAuth2Constants.KEY_ERROR) != null
                        || mResultTokenMap.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null) {
                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);

                } else {
                    result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
                    ArrayList<Object> data = new ArrayList<>();
                    data.add(mResultTokenMap);
                    result.setData(data);
                }

            } else {
                client.exhaustResponse(postMethod.getResponseBodyAsStream());
                result = new RemoteOperationResult(false, status, postMethod.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (postMethod != null)
            postMethod.releaseConnection(); // let the connection available for other methods

        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());

        } else if (result.getException() != null) {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage(),
                    result.getException());

        } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
            Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code "
                    + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": "
                    + ((mResultTokenMap != null) ? mResultTokenMap.get(OAuth2Constants.KEY_ERROR) : "NULL"));

        } else {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());
        }
    }

    return result;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a standard POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///w  w  w . j av  a2 s.com
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {
    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {
        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {
            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {}));
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same standard POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the POST data to be sent via the {@link PostMethod}
 *//* ww w.j ava2 s. c o  m*/
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {

    _log.debug("handleStandardPost()");

    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {

        StringBuffer debugMsg = new StringBuffer();
        debugMsg.append("Post param: " + stringParameterName);

        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {

            debugMsg.append(" \"" + stringParamterValue + "\"");

            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
        _log.debug(debugMsg.toString());
    }
    // Set the proxy request POST data 
    postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {}));
}

From source file:com.novell.ldap.DsmlConnection.java

/**
 *Allows for a pre-build DSMLv2 Document to be sent over
 *the wire.  Usefull when doing batch requests
 * @param DSML The String version of the DSMLv2
 * @return List of results// w  w w.ja va2 s  .  c o  m
 * @throws LDAPException
 */
public ArrayList sendDoc(String DSML) throws LDAPException {
    ArrayList results = new ArrayList();
    try {
        PostMethod post = new PostMethod(serverString);
        //post.setDoAuthentication(true);

        //First load up the content headers
        post.setRequestHeader("Content-Type", "text/xml; charset=utf8");
        if (this.useSoap) {
            post.setRequestHeader("SOAPAction", "#batchRequest");
        }

        if (this.callback != null) {
            this.callback.manipulationPost(post, this);
        }

        StringWriter out = new StringWriter();

        PrintWriter pout = new PrintWriter(out);

        //First print the SOAP Envelope 
        pout.println("<?xml version=\"1.0\" encoding=\"UTF8\"?>");
        if (this.useSoap) {
            pout.println("<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            pout.println("<soap-env:Body>");
        }
        //write out the message
        //writer.writeMessage(message);
        //writer.finish();
        pout.write(DSML);

        if (this.useSoap) {
            //Complete the SOAP Envelope
            pout.println("</soap-env:Body>");
            pout.println("</soap-env:Envelope>");
        }
        StringBufferInputStream in = new StringBufferInputStream(out.toString());
        //Set the input stream

        post.setRequestBody(in);

        //POST the request
        con.executeMethod(post);

        DSMLReader reader = new DSMLReader(post.getResponseBodyAsStream());

        post.releaseConnection();

        //Make sure it was successfull
        /*LDAPException e = reader.
        if (e != null) throw e;*/

        ArrayList errors = reader.getErrors();
        if (errors.size() > 0) {
            throw ((LDAPException) errors.get(0));
        }

        LDAPMessage msg;
        while ((msg = reader.readMessage()) != null) {
            results.add(msg);
        }

    } catch (HttpException e) {
        throw new LDAPLocalException("Http Error", LDAPException.CONNECT_ERROR, e);
    } catch (IOException e) {
        throw new LDAPLocalException("Communications Error", LDAPException.CONNECT_ERROR, e);
    }

    return results;
}

From source file:com.novell.ldap.DsmlConnection.java

/**
 * Used to send requests to the server and retrieve responses
 * @param message The Message To Send/* ww  w.  j a va  2 s  .  c  o m*/
 * @param isSearch true if returning a DSMLSearchResult, false if LDAPMessage
 * @return The Server's Response
 */
private Object sendMessage(LDAPMessage message, boolean isSearch) throws LDAPException {
    try {
        PostMethod post = new PostMethod(serverString);
        //post.setDoAuthentication(true);

        //First load up the content headers
        post.setRequestHeader("Content-Type", "text/xml; charset=utf8");
        if (this.useSoap) {
            post.setRequestHeader("SOAPAction", "#batchRequest");
        }

        if (this.callback != null) {
            this.callback.manipulationPost(post, this);
        }

        StringWriter out = new StringWriter();

        DSMLWriter writer = new DSMLWriter(out);

        PrintWriter pout = new PrintWriter(out);

        //First print the SOAP Envelope 
        pout.println("<?xml version=\"1.0\" encoding=\"UTF8\"?>");
        if (this.useSoap) {
            pout.println("<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            pout.println("<soap-env:Body>");
        }

        //write out the message
        writer.writeMessage(message);
        writer.finish();

        if (this.useSoap) {
            //Complete the SOAP Envelope
            pout.println("</soap-env:Body>");
            pout.println("</soap-env:Envelope>");
        }

        ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes("UTF-8"));
        //Set the input stream

        post.setRequestBody(in);

        //POST the request
        con.executeMethod(post);

        if (post.getStatusCode() != 200) {
            //we have an error, if it's an authorization error throw an invalid credentials exception.  otherwise throw an unwilling to perform.
            if (post.getStatusCode() == 401 || post.getStatusCode() == 403) {
                throw new LDAPException(LDAPException.resultCodeToString(LDAPException.INVALID_CREDENTIALS),
                        LDAPException.INVALID_CREDENTIALS,
                        LDAPException.resultCodeToString(LDAPException.INVALID_CREDENTIALS));
            } else {
                throw new LDAPException(LDAPException.resultCodeToString(LDAPException.UNAVAILABLE),
                        LDAPException.UNAVAILABLE, post.getStatusText());
            }
        }

        DSMLReader reader = new DSMLReader(post.getResponseBodyAsStream());

        post.releaseConnection();

        //Make sure it was successfull
        ArrayList errors = reader.getErrors();
        if (errors.size() > 0) {
            throw ((LDAPException) errors.get(0));
        }

        if (isSearch) {
            return new DSMLSearchResults(reader);
        } else {
            //return the message
            return reader.readMessage();
        }
    } catch (HttpException e) {
        throw new LDAPLocalException("Http Error", LDAPException.CONNECT_ERROR, e);
    } catch (IOException e) {
        throw new LDAPLocalException("Communications Error", LDAPException.CONNECT_ERROR, e);
    }
}

From source file:com.intranet.intr.EmpControllerProyecto.java

private void smsenvio(String nif, String mensaje) {
    try {//from  w ww.j  a v a  2 s. c o  m
        clientes cli = clientesService.ByNif(nif);
        //map.addAttribute("msg","success");
        HttpClient client = new HttpClient();
        client.setStrictMode(true);
        //Se fija el tiempo maximo de espera de la respuesta del servidor
        client.setTimeout(60000);
        //Se fija el tiempo maximo de espera para conectar con el servidor
        client.setConnectionTimeout(5000);
        PostMethod post = null;
        //Se fija la URL sobre la que enviar la peticion POST
        //Como ejemplo la peticion se enva a www.altiria.net/sustituirPOSTsms
        //Se debe reemplazar la cadena /sustituirPOSTsms por la parte correspondiente
        //de la URL suministrada por Altiria al dar de alta el servicio
        post = new PostMethod("http://www.altiria.net/api/http");
        //Se fija la codificacion de caracteres en la cabecera de la peticion
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //Se crea la lista de parametros a enviar en la peticion POST
        NameValuePair[] parametersList = new NameValuePair[6];
        //XX, YY y ZZ se corresponden con los valores de identificacion del
        //usuario en el sistema.
        parametersList[0] = new NameValuePair("cmd", "sendsms");
        parametersList[1] = new NameValuePair("domainId", "comercial");
        parametersList[2] = new NameValuePair("login", "jfruano");
        parametersList[3] = new NameValuePair("passwd", "wrnkmekt");
        parametersList[4] = new NameValuePair("dest", "34" + cli.getTelefono());
        parametersList[5] = new NameValuePair("msg", "" + mensaje);
        //Se rellena el cuerpo de la peticion POST con los parametros
        post.setRequestBody(parametersList);
        int httpstatus = 0;
        String response = null;
        try {
            //Se enva la peticion
            httpstatus = client.executeMethod(post);
            //Se consigue la respuesta
            response = post.getResponseBodyAsString();
        } catch (Exception e) {
            //Habra que prever la captura de excepciones

        } finally {
            //En cualquier caso se cierra la conexion
            post.releaseConnection();
        }
        //Habra que prever posibles errores en la respuesta del servidor
        if (httpstatus != 200) {

        } else {
            //Se procesa la respuesta capturada en la cadena response
        }
    } catch (Exception ex) {
        ex.printStackTrace();

    }
}

From source file:edu.harvard.iq.dvn.core.web.dvnremote.DvnTermsOfUseAccess.java

public String dvnAcceptRemoteTOU(String TOUurl, String jsessionid, String downloadURL, String extraCookies) {

    GetMethod TOUgetMethod = null;//from  w  w  w.jav a  2  s  .co  m
    PostMethod TOUpostMethod = null;
    GetMethod redirectGetMethod = null;

    String compatibilityPrefix = "";
    Boolean compatibilityMode = false;

    Matcher matcher = null;

    String remotehosturl = null;
    String remotehost = null;
    String regexpRemoteHostURL = "(https*://[^/]*/)";
    Pattern patternRemoteHostURL = Pattern.compile(regexpRemoteHostURL);

    if (downloadURL != null) {
        matcher = patternRemoteHostURL.matcher(downloadURL);
        if (matcher.find()) {
            remotehosturl = matcher.group(1);
            dbgLog.fine("TOU found remote url: " + remotehosturl);
        }
    }

    try {

        TOUgetMethod = new GetMethod(TOUurl);
        if (jsessionid != null) {
            TOUgetMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
        } else {
            // Do we have a cached jsessionid? 
            String cachedJsessionID = null;

            if (remotehosturl != null) {
                String regexpRemoteHost = "https*://([^/]*)/";
                Pattern patternRemoteHost = Pattern.compile(regexpRemoteHost);

                matcher = patternRemoteHost.matcher(remotehosturl);
                if (matcher.find()) {
                    remotehost = matcher.group(1);

                    cachedJsessionID = getCachedJsessionID(remotehost);
                    if (cachedJsessionID != null) {

                        TOUgetMethod.addRequestHeader("Cookie", "JSESSIONID=" + cachedJsessionID);
                        jsessionid = cachedJsessionID;
                    }
                }
            }
        }

        if (extraCookies != null) {
            TOUgetMethod.addRequestHeader("Cookie", extraCookies);
        }

        String icesession = null;
        String iceview = null;
        String facesviewstate = null;
        String studyid = null;
        String remotefileid = null;

        String iceFacesUpdate = null;

        /* 
         * As of DVN 3.0 (and IceFaces 3.*), the following has changed: 
         *  icesession - no longer used;
         *  ice.window - appears to have replaced the above;
         *  the old regex pattern for ViewState no longer works (see below);
         *  in fact, javax.faces.ViewState and ice.view must be 
         *  treated as separate parameters! (again, see below)
         *  (the last one needs to be verified; there's a chance that 
         *  javax.faces.ViewState is still not necessary... -- L.A.)
         * 
         * TODO: add re-test with DVN 2.* and make sure backward compatibility
         * mechanism is in place. -- L.A.
         *  
         */

        String regexpRemoteFileId = "(/FileDownload.*)";
        String regexpJsession = "JSESSIONID=([^;]*);";

        /* old ice.session; no longer used in 3.0:
        String regexpIceSession = "session: \'([^\']*)\'";
         */

        /* ice.window, appears to have replaced ice.session above:
         */
        String regexpIceSession = "input [^>]*ice.window\"[^>]*value=\"([^\"]*)\"";

        /* ice.view pattern, changed:
        String regexpIceViewState = "view: ([^,]*),"; 
         */
        String regexpIceViewState = "<input [^>]*ice.view\"[^>]*value=\"([^\"]*)\"";

        /* New in DVN/IceFaces 3.*: separate pattern of javax.faces.ViewState:
         */
        String regexpFacesViewState = "<input [^>]*ViewState\"[^>]*value=\"([^\"]*)\"";

        String regexpStudyId = "studyId\"[^>]*value=\"([0-9]*)\"";
        //String regexpRemoteFileId = "(/FileDownload.*fileId=[0-9]*)";
        String regexpOldStyleForm = "content:termsOfUsePageView:";

        Pattern patternJsession = Pattern.compile(regexpJsession);
        Pattern patternRemoteFileId = Pattern.compile(regexpRemoteFileId);

        Pattern patternIceSession = Pattern.compile(regexpIceSession);
        Pattern patternIceViewState = Pattern.compile(regexpIceViewState);
        Pattern patternFacesViewState = Pattern.compile(regexpFacesViewState);
        Pattern patternStudyId = Pattern.compile(regexpStudyId);
        Pattern patternOldStyleForm = Pattern.compile(regexpOldStyleForm);

        int status = getClient().executeMethod(TOUgetMethod);

        for (int i = 0; i < TOUgetMethod.getResponseHeaders().length; i++) {
            String headerName = TOUgetMethod.getResponseHeaders()[i].getName();
            //dbgLog.info("TOU found header: "+headerName); 

            if (headerName.equals("Set-Cookie")) {

                String cookieHeader = TOUgetMethod.getResponseHeaders()[i].getValue();
                dbgLog.fine("TOU found cookie header: " + cookieHeader);

                matcher = patternJsession.matcher(cookieHeader);
                if (matcher.find()) {
                    jsessionid = matcher.group(1);
                    dbgLog.fine("TOU - jsessionid issued (as a cookie): " + jsessionid);

                    // TODO: 
                    // Any scenarios where we would want to cache it here? 
                    // -L.A.
                }
            }
        }

        InputStream in = TOUgetMethod.getResponseBodyAsStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));

        String line = null;

        if (downloadURL != null) {
            matcher = patternRemoteFileId.matcher(downloadURL);
            if (matcher.find()) {
                remotefileid = matcher.group(1);
                dbgLog.fine("TOU found remotefileid: " + remotefileid);
            }
            if (remotehosturl != null) {
                // The update URL, below, only works with IceFaces < 2.0, 
                // i.e., only if the remote DVN is v2.*:
                //iceFacesUpdate = remoteurl + "dvn/block/send-receive-updates";
                // For IceFaces and DVN 3.*, the POST must be submitted to 
                // the terms of use page itself:
                // (needs to be verified -- L.A.)
                iceFacesUpdate = remotehosturl + "dvn/faces/study/TermsOfUsePage.xhtml";
            }
        }

        while ((line = rd.readLine()) != null) {
            matcher = patternIceSession.matcher(line);
            if (matcher.find()) {
                icesession = matcher.group(1);
                dbgLog.fine("TOU found icesession: " + icesession);
            }
            matcher = patternIceViewState.matcher(line);
            if (matcher.find()) {
                iceview = matcher.group(1);
                dbgLog.fine("TOU found ice view: " + iceview);
            }
            matcher = patternFacesViewState.matcher(line);
            if (matcher.find()) {
                facesviewstate = matcher.group(1);
                dbgLog.fine("TOU found faces view state: " + facesviewstate);
            }
            matcher = patternStudyId.matcher(line);
            if (matcher.find()) {
                studyid = matcher.group(1);
                dbgLog.fine("TOU found study id: " + studyid);
            }
            if (!compatibilityMode) {
                matcher = patternOldStyleForm.matcher(line);
                if (matcher.find()) {
                    compatibilityMode = true;
                }
            }
        }

        //if ( compatibilityMode ) {
        //   compatibilityPrefix = "content:termsOfUsePageView:";
        //}

        rd.close();
        TOUgetMethod.releaseConnection();

        if (jsessionid != null) {

            // We have either been issued a new JSESSIONID, or had one
            // cached for this host, or 
            // already had a JSESSIONID issued
            // to us when we logged in. Either way we can 
            // now make the final call agreeing to
            // to the Terms of Use;
            // it has to be a POST method: 

            TOUpostMethod = new PostMethod(iceFacesUpdate);
            //TOUurl = TOUurl.substring(0, TOUurl.indexOf( "?" )); 
            //TOUpostMethod = new PostMethod( TOUurl + ";jsessionid=" + jsessionid ); 
            dbgLog.fine("icefaces url: " + iceFacesUpdate);

            TOUpostMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
            if (extraCookies != null) {
                TOUpostMethod.addRequestHeader("Cookie", extraCookies);
            }

            TOUpostMethod.setFollowRedirects(false);

            NameValuePair[] postParameters = {
                    /* new in 3.0: ViewState different from ice.view: */
                    new NameValuePair("javax.faces.ViewState", facesviewstate),
                    /* new in 3.0: no longer necessary: 
                    new NameValuePair( "javax.faces.RenderKitId", "ICEfacesRenderKit" ),
                     */
                    /* new in 3.0: no longer necessary: 
                    new NameValuePair( "ice.submit.partial", "false" ),
                     */
                    new NameValuePair("icefacesCssUpdates", ""),
                    /* new in 3.0: ice.window instead of icesession: */
                    new NameValuePair("ice.window", icesession),
                    /* new in 3.0: ice.view different from viewstate: */
                    new NameValuePair("ice.view", iceview), new NameValuePair("ice.focus", "form1:termsButton"),

                    new NameValuePair("pageName", "TermsOfUsePage"),

                    new NameValuePair("form1", "form1"),

                    new NameValuePair("form1:vdcId", ""), new NameValuePair("form1:studyId", studyid),
                    new NameValuePair("form1:redirectPage", remotefileid),
                    new NameValuePair("form1:tou", "download"), new NameValuePair("form1:termsAccepted", "on"),
                    new NameValuePair("form1:termsButton", "Continue") };

            // TODO: 

            // no need to set the redirectPage parameter, if there's 
            // no filedownload url. 

            TOUpostMethod.setRequestBody(postParameters);

            status = getClient().executeMethod(TOUpostMethod);

            dbgLog.fine("TOU Post status: " + status);

            // Now the TOU system is going to redirect
            // us to the actual download URL. 
            // Note that it can be MORE THAN ONE 
            // redirects (first to the homepage, then
            // eventually to the file download url); 
            // So we want to just keep following the
            // redirect until we get the file. 
            // But just in case, we'll be counting the
            // redirect hoops to make sure we're not
            // stuck in a loop. 

            String redirectLocation = null;

            if (status == 302) {
                for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) {
                    String headerName = TOUpostMethod.getResponseHeaders()[i].getName();
                    if (headerName.equals("Location")) {
                        redirectLocation = TOUpostMethod.getResponseHeaders()[i].getValue();
                    }
                }
            } else if (status == 200) {
                for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) {
                    String headerName = TOUpostMethod.getResponseHeaders()[i].getName();
                    dbgLog.fine("TOU post header: " + headerName + "="
                            + TOUpostMethod.getResponseHeaders()[i].getValue());
                }
                dbgLog.fine("TOU trying to read output of the post method;");
                InputStream pin = TOUpostMethod.getResponseBodyAsStream();
                BufferedReader prd = new BufferedReader(new InputStreamReader(pin));

                String pline = null;

                while ((pline = prd.readLine()) != null) {
                    dbgLog.fine("TOU read line: " + pline);
                }
                prd.close();
            }

            TOUpostMethod.releaseConnection();

            int counter = 0;

            while (status == 302 && counter < 10 && (!(redirectLocation.matches(".*FileDownload.*")))) {

                redirectGetMethod = new GetMethod(redirectLocation);
                redirectGetMethod.setFollowRedirects(false);
                redirectGetMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
                if (extraCookies != null) {
                    redirectGetMethod.addRequestHeader("Cookie", extraCookies);
                }

                status = getClient().executeMethod(redirectGetMethod);

                if (status == 302) {
                    for (int i = 0; i < redirectGetMethod.getResponseHeaders().length; i++) {
                        String headerName = redirectGetMethod.getResponseHeaders()[i].getName();
                        if (headerName.equals("Location")) {
                            redirectLocation = redirectGetMethod.getResponseHeaders()[i].getValue();
                        }
                    }
                }
                redirectGetMethod.releaseConnection();
                counter++;

            }

        }

    } catch (IOException ex) {
        if (redirectGetMethod != null) {
            redirectGetMethod.releaseConnection();
        }
        if (TOUgetMethod != null) {
            TOUgetMethod.releaseConnection();
        }
        if (TOUpostMethod != null) {
            TOUpostMethod.releaseConnection();
        }
        return null;
    }

    dbgLog.fine("TOU: returning jsessionid=" + jsessionid);

    return jsessionid;
}

From source file:net.ushkinaz.storm8.http.GameRequestor.java

/**
 * Creates PostMethod.//from  www.j av a2 s . co  m
 *
 * @param requestURL      url to request
 * @param postBodyFactory create body
 * @return post method
 */
protected PostMethod createPostMethod(String requestURL, PostBodyFactory postBodyFactory) {
    //TODO: add PostMethod pooling

    PostMethod postMethod = new PostMethod(requestURL);
    postMethod.addRequestHeader("Referer", requestURL);
    postMethod.addRequestHeader("Origin", player.getGame().getGameURL());
    postMethod.addRequestHeader("Accept", ACCEPT);
    postMethod.addRequestHeader("Content-type", CONTENT_TYPE);
    postMethod.addRequestHeader("Accept-Charset", ACCEPT_CHARSET);

    postMethod.setRequestBody(postBodyFactory.createBody());
    return postMethod;
}

From source file:nl.cwi.monetdb.xquery.xrpc.api.XRPCHTTPConnection.java

/** 
 * Sends the given XRPC request over an HTTP connection 
 * to the destination server and returns the server's 
        //from  w  w w .j a  v  a  2  s  .c o  m
 * response message, which can be an XRPC response message or a SOAP 
 * Fault message, in a StringBuffer. 
 * 
 * @param server URL of the destination XRPC server 
 * @param request The (XRPC) request to send 
 * @return Server's response message, which can be an XRPC response 
 * message or a SOAP Fault message. 
 * @throws IOException If an I/O error occurs 
 */
public static StringBuffer sendReceive(String server, String request) throws IOException {
    URL url = new URL(server);

    PostMethod pmethod = new PostMethod(server);

    //        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
    //        httpConn.setDoInput(true); 
    //        httpConn.setDoOutput(true); 
    //        httpConn.setUseCaches(false); 
    //        httpConn.setRequestMethod("POST"); 

    //        httpConn.setRequestProperty("Content-Type", 
    //                                    "application/x-www-form-urlencoded"); 

    pmethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    //        httpConn.setRequestProperty("Content-Length", request.length()+""); 
    //        httpConn.connect(); 

    /* Send POST output. */
    //        DataOutputStream printout = new 
    //            DataOutputStream(httpConn.getOutputStream()); 
    //        printout.writeBytes(request); 
    //        printout.flush (); 
    pmethod.setRequestBody(request);

    HttpClient client = new HttpClient();
    int status = client.executeMethod(pmethod);

    StringBuffer response = new StringBuffer();

    InputStreamReader is = new InputStreamReader(pmethod.getResponseBodyAsStream());
    char[] buf = new char[1024];
    int len;
    while ((len = is.read(buf, 0, 1024)) > 0) {
        response.append(buf, 0, len);
    }

    /* Get response data. */
    //        InputStreamReader isReader; 
    //        StringBuffer response = new StringBuffer(16384); 
    //        if(httpConn.getResponseCode() != HttpURLConnection.HTTP_OK){ 
    //      System.out.println(httpConn.getResponseCode()); 
    //      System.out.println(httpConn.getResponseMessage()); 
    /* Read the SOAP Fault message. */
    //            isReader = new InputStreamReader(httpConn.getErrorStream()); 
    //        } else { 
    /* Read the response message, which can also be a SOAP Fault 
     * message. */
    //            isReader = new InputStreamReader(httpConn.getInputStream()); 
    //        } 
    //        int c; 
    //        while( (c = isReader.read()) >= 0) response.append((char)c); 
    //        isReader.close(); 
    //        printout.close();
    return response;
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected HttpMethod getMethod(URI uri, String message, ParameterValueList parameters,
        Map<String, String> headersParamsMap) throws SenderException {
    try {//from   w  ww  .  j  a  v  a2s .c om
        boolean queryParametersAppended = false;
        if (isEncodeMessages()) {
            message = URLEncoder.encode(message);
        }

        StringBuffer path = new StringBuffer(uri.getPath());
        if (!StringUtils.isEmpty(uri.getQuery())) {
            path.append("?" + uri.getQuery());
            queryParametersAppended = true;
        }

        if (getMethodType().equals("GET")) {
            if (parameters != null) {
                queryParametersAppended = appendParameters(queryParametersAppended, path, parameters,
                        headersParamsMap);
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "path after appending of parameters [" + path.toString() + "]");
            }
            GetMethod result = new GetMethod(path + (parameters == null ? message : ""));
            for (String param : headersParamsMap.keySet()) {
                result.addRequestHeader(param, headersParamsMap.get(param));
            }
            if (log.isDebugEnabled())
                log.debug(
                        getLogPrefix() + "HttpSender constructed GET-method [" + result.getQueryString() + "]");
            return result;
        } else if (getMethodType().equals("POST")) {
            PostMethod postMethod = new PostMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                postMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            for (String param : headersParamsMap.keySet()) {
                postMethod.addRequestHeader(param, headersParamsMap.get(param));
            }
            postMethod.setRequestBody(message);

            return postMethod;
        }
        if (getMethodType().equals("PUT")) {
            PutMethod putMethod = new PutMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                putMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            putMethod.setRequestBody(message);
            return putMethod;
        }
        if (getMethodType().equals("DELETE")) {
            DeleteMethod deleteMethod = new DeleteMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                deleteMethod.setRequestHeader("Content-Type", getContentType());
            }
            return deleteMethod;
        }
        if (getMethodType().equals("HEAD")) {
            HeadMethod headMethod = new HeadMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                headMethod.setRequestHeader("Content-Type", getContentType());
            }
            return headMethod;
        }
        if (getMethodType().equals("REPORT")) {
            Element element = XmlUtils.buildElement(message, true);
            ReportInfo reportInfo = new ReportInfo(element, 0);
            ReportMethod reportMethod = new ReportMethod(path.toString(), reportInfo);
            if (StringUtils.isNotEmpty(getContentType())) {
                reportMethod.setRequestHeader("Content-Type", getContentType());
            }
            return reportMethod;
        }
        throw new SenderException(
                "unknown methodtype [" + getMethodType() + "], must be either POST, GET, PUT or DELETE");
    } catch (URIException e) {
        throw new SenderException(getLogPrefix() + "cannot find path from url [" + getUrl() + "]", e);
    } catch (DavException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    }
}