alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/methods/PostMethod.java,v 1.45.2.5 2004/02/22 18:21:15 olegk Exp $
 * $Revision: 1.45.2.5 $
 * $Date: 2004/02/22 18:21:15 $
 *
 * ====================================================================
 *
 *  Copyright 1999-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * .
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */
package org.apache.commons.httpclient.methods;

import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpConstants;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Implements the HTTP POST method.
 * 

* The HTTP POST method is defined in section 9.5 of * RFC1945: *

* The POST method is used to request that the origin server accept the entity * enclosed in the request as a new subordinate of the resource identified by * the Request-URI in the Request-Line. POST is designed to allow a uniform * method to cover the following functions: *
    *
  • Annotation of existing resources
  • *
  • Posting a message to a bulletin board, newsgroup, mailing list, or * similar group of articles
  • *
  • Providing a block of data, such as the result of submitting a form, * to a data-handling process
  • *
  • Extending a database through an append operation
  • *
*
*

* * @author Remy Maucherat * @author Doug Sale * @author Jeff Dever * @author Ortwin Glück * @author Mike Bowler * @author Oleg Kalnichevski * * @version $Revision: 1.45.2.5 $ * @since 1.0 */ public class PostMethod extends EntityEnclosingMethod { // -------------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(PostMethod.class); /** The Content-Type for www-form-urlencoded. */ public static final String FORM_URL_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"; /** * The buffered request body consisting of NameValuePairs. */ private Vector params = new Vector(); // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 1.0 */ public PostMethod() { super(); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public PostMethod(String uri) { super(uri); } /** * Constructor specifying a URI and a tempDir. * * @param uri either an absolute or relative URI * @param tempDir directory to store temp files in * * @deprecated the client is responsible for disk I/O * @since 1.0 */ public PostMethod(String uri, String tempDir) { super(uri, tempDir); } /** * Constructor specifying a URI, tempDir and tempFile. * * @param uri either an absolute or relative URI * @param tempDir directory to store temp files in * @param tempFile file to store temporary data in * * @deprecated the client is responsible for disk I/O * @since 1.0 */ public PostMethod(String uri, String tempDir, String tempFile) { super(uri, tempDir, tempFile); } // ----------------------------------------------------- Instance Methods /** * Returns "POST". * * @return "POST" * * @since 2.0 */ public String getName() { return "POST"; } /** * Returns true if there is a request body to be sent. * *

This method must be overwritten by sub-classes that implement * alternative request content input methods *

* * @return boolean * * @since 2.0beta1 */ protected boolean hasRequestContent() { LOG.trace("enter PostMethod.hasRequestContent()"); if (!this.params.isEmpty()) { return true; } else { return super.hasRequestContent(); } } /** * Clears request body. * *

This method must be overwritten by sub-classes that implement * alternative request content input methods

* * @since 2.0beta1 */ protected void clearRequestBody() { LOG.trace("enter PostMethod.clearRequestBody()"); this.params.clear(); super.clearRequestBody(); } /** * Generates the request body. * *

This method must be overwritten by sub-classes that implement * alternative request content input methods *

* * @return request body as an array of bytes. If the request content * has not been set, returns null. * * @since 2.0beta1 */ protected byte[] generateRequestBody() { LOG.trace("enter PostMethod.renerateRequestBody()"); if (!this.params.isEmpty()) { String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); return HttpConstants.getContentBytes(content); } else { return super.generateRequestBody(); } } /** * Sets the value of parameter with parameterName to parameterValue. This method * does not preserve the initial insertion order. * * @param parameterName name of the parameter * @param parameterValue value of the parameter * * @since 2.0 */ public void setParameter(String parameterName, String parameterValue) { LOG.trace("enter PostMethod.setParameter(String, String)"); removeParameter(parameterName); addParameter(parameterName, parameterValue); } /** * Gets the parameter of the specified name. If there exists more than one * parameter with the name paramName, then only the first one is returned. * * @param paramName name of the parameter * * @return If a parameter exists with the name argument, the coresponding * NameValuePair is returned. Otherwise null. * * @since 2.0 * */ public NameValuePair getParameter(String paramName) { LOG.trace("enter PostMethod.getParameter(String)"); if (paramName == null) { return null; } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair parameter = (NameValuePair) iter.next(); if (paramName.equals(parameter.getName())) { return parameter; } } return null; } /** * Gets the parameters currently added to the PostMethod. If there are no * parameters, a valid array is returned with zero elements. The returned * array object contains an array of pointers to the internal data * members. * * @return An array of the current parameters * * @since 2.0 * */ public NameValuePair[] getParameters() { LOG.trace("enter PostMethod.getParameters()"); int numPairs = this.params.size(); Object[] objectArr = this.params.toArray(); NameValuePair[] nvPairArr = new NameValuePair[numPairs]; for (int i = 0; i < numPairs; i++) { nvPairArr[i] = (NameValuePair) objectArr[i]; } return nvPairArr; } /** * Adds a new parameter to be used in the POST request body. * * @param paramName The parameter name to add. * @param paramValue The parameter value to add. * * @throws IllegalArgumentException if either argument is null * * @since 1.0 */ public void addParameter(String paramName, String paramValue) throws IllegalArgumentException { LOG.trace("enter PostMethod.addParameter(String, String)"); if ((paramName == null) || (paramValue == null)) { throw new IllegalArgumentException( "Arguments to addParameter(String, String) cannot be null"); } super.clearRequestBody(); this.params.add(new NameValuePair(paramName, paramValue)); } /** * Adds a new parameter to be used in the POST request body. * * @param param The parameter to add. * * @throws IllegalArgumentException if the argument is null or contains * null values * * @since 2.0 */ public void addParameter(NameValuePair param) throws IllegalArgumentException { LOG.trace("enter PostMethod.addParameter(NameValuePair)"); if (param == null) { throw new IllegalArgumentException("NameValuePair may not be null"); } addParameter(param.getName(), param.getValue()); } /** * Adds an array of parameters to be used in the POST request body. Logs a * warning if the parameters argument is null. * * @param parameters The array of parameters to add. * * @since 2.0 */ public void addParameters(NameValuePair[] parameters) { LOG.trace("enter PostMethod.addParameters(NameValuePair[])"); if (parameters == null) { LOG.warn("Attempt to addParameters(null) ignored"); } else { super.clearRequestBody(); for (int i = 0; i < parameters.length; i++) { this.params.add(parameters[i]); } } } /** * Removes all parameters with the given paramName. If there is more than * one parameter with the given paramName, all of them are removed. If * there is just one, it is removed. If there are none, then the request * is ignored. * * @param paramName The parameter name to remove. * * @return true if at least one parameter was removed * * @throws IllegalArgumentException When the parameter name passed is null * * @since 2.0 */ public boolean removeParameter(String paramName) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String)"); if (paramName == null) { throw new IllegalArgumentException( "Argument passed to removeParameter(String) cannot be null"); } boolean removed = false; Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName())) { iter.remove(); removed = true; } } return removed; } /** * Removes all parameter with the given paramName and paramValue. If there * is more than one parameter with the given paramName, only one is * removed. If there are none, then the request is ignored. * * @param paramName The parameter name to remove. * @param paramValue The parameter value to remove. * * @return true if a parameter was removed. * * @throws IllegalArgumentException when param name or value are null * * @since 2.0 */ public boolean removeParameter(String paramName, String paramValue) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String, String)"); if (paramName == null) { throw new IllegalArgumentException("Parameter name may not be null"); } if (paramValue == null) { throw new IllegalArgumentException("Parameter value may not be null"); } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName()) && paramValue.equals(pair.getValue())) { iter.remove(); return true; } } return false; } /** * Sets an array of parameters to be used in the POST request body * * @param parametersBody The array of parameters to add. * * @throws IllegalArgumentException when param parameters are null * * @since 2.0beta1 */ public void setRequestBody(NameValuePair[] parametersBody) throws IllegalArgumentException { LOG.trace("enter PostMethod.setRequestBody(NameValuePair[])"); if (parametersBody == null) { throw new IllegalArgumentException("Array of parameters may not be null"); } clearRequestBody(); addParameters(parametersBody); } /** * Adds Content Type: application/x-www-form-urlencoded header in * addition to the "standard" set of headers, if no Content Type * header has been set by the user * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs * @throws HttpException if a protocol exception occurs. * @throws HttpRecoverableException if a recoverable transport error occurs. * Usually this kind of exceptions can be recovered from by * retrying the HTTP method * * @since 2.0 */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { super.addRequestHeaders(state, conn); if (!this.params.isEmpty()) { //there are some parameters, so set the contentType header if (getRequestHeader("Content-Type") == null) { setRequestHeader("Content-Type", FORM_URL_ENCODED_CONTENT_TYPE); } } } }
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.