Skip to content

Commit

Permalink
Support posting form data in webservice requests
Browse files Browse the repository at this point in the history
  • Loading branch information
gschueler committed Apr 10, 2012
1 parent c41f280 commit 054d4b2
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 10 deletions.
Expand Up @@ -26,6 +26,7 @@

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.log4j.Category;
Expand Down Expand Up @@ -105,6 +106,11 @@ protected RequestEntity getRequestEntity(PostMethod method) {
return null;
}

@Override
protected NameValuePair[] getRequestBody(PostMethod method) {
return new NameValuePair[0];
}

protected boolean isPostMethod() {
return false;
}
Expand Down
33 changes: 26 additions & 7 deletions core/src/main/java/com/dtolabs/client/utils/HttpClientChannel.java
Expand Up @@ -211,6 +211,12 @@ private void setHeaders(Map map) {
*/
protected abstract RequestEntity getRequestEntity(PostMethod method);

/**
* subclasses should return a byte[] of data, or null. This will only be called if the {@link #isPostMethod()} method
* returns true.
*/
protected abstract NameValuePair[] getRequestBody(PostMethod method);

/**
* Return true if the request method is POST.
* @return
Expand Down Expand Up @@ -295,19 +301,28 @@ public void makeRequest() throws IOException, HttpClientException {

requestMade = true;
RequestEntity reqEntity=null;
NameValuePair[] postBody=null;
if (isPostMethod()) {
setMethodType("POST");
}
HttpMethod method = initMethod();
if(isPostMethod()){
reqEntity = getRequestEntity((PostMethod)method);
logger.debug("preparing to post request entity data: " + reqEntity.getContentType());
((PostMethod) method).setRequestEntity(reqEntity);
if(null!=reqEntity){
logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

((PostMethod) method).setRequestEntity(reqEntity);
}else{
logger.debug("preparing to post form data" );
postBody = getRequestBody((PostMethod)method);
((PostMethod) method).setRequestBody(postBody);
}
}
logger.debug("calling preMakeRequest");
if (!preMakeRequest(method)) {
return;
}
logger.debug("calling doAuthentication...");
if(!doAuthentication(method)){
return;
}
Expand All @@ -316,21 +331,25 @@ public void makeRequest() throws IOException, HttpClientException {
if(!isPostMethod()){
method.setFollowRedirects(true);
}
logger.debug("make request...");
resultCode = httpc.executeMethod(method);
reasonCode = method.getStatusText();
if(isPostMethod()){
//check redirect after post
method = checkFollowRedirect(method);
method = checkFollowRedirect(method,resultCode);
}
logger.debug("check needs reauth...");

if(needsReAuthentication(resultCode,method)){
logger.debug("re-authentication needed, performing...");
method.releaseConnection();
method.abort();
//need to re-authenticate.
method = initMethod();
if (isPostMethod()) {
if (isPostMethod() && null!=reqEntity) {
((PostMethod) method).setRequestEntity(reqEntity);
}else if (isPostMethod() && null!=postBody) {
((PostMethod) method).setRequestBody(postBody);
}
if(!doAuthentication(method)){
//user login failed
Expand All @@ -349,11 +368,12 @@ public void makeRequest() throws IOException, HttpClientException {
}
}

logger.debug("finish...");
if (null != method.getResponseHeader("Content-Type")) {
resultType = method.getResponseHeader("Content-Type").getValue();
}
String type = resultType;
if (type.indexOf(";") > 0) {
if (type != null && type.indexOf(";") > 0) {
type = type.substring(0, type.indexOf(";")).trim();
}
if (null==expectedContentType || expectedContentType.equals(type)) {
Expand Down Expand Up @@ -387,9 +407,8 @@ public void makeRequest() throws IOException, HttpClientException {
postMakeRequest();
}

private HttpMethod checkFollowRedirect(final HttpMethod method) throws IOException, HttpClientException {
private HttpMethod checkFollowRedirect(final HttpMethod method, final int res) throws IOException, HttpClientException {

final int res = httpc.executeMethod(method);
if ((res == HttpStatus.SC_MOVED_TEMPORARILY) ||
(res == HttpStatus.SC_MOVED_PERMANENTLY) ||
(res == HttpStatus.SC_SEE_OTHER) ||
Expand Down
Expand Up @@ -25,6 +25,7 @@


import com.dtolabs.rundeck.core.CoreException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
Expand All @@ -38,6 +39,7 @@
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Map;


Expand All @@ -61,6 +63,7 @@ class WebserviceHttpClientChannel extends BaseHttpClientChannel implements Webse
String responseMessage = null;
private Document resultDoc = null;
private File uploadFile = null;
private Map<String,String> formData=null;
private String fileparam = null;

/**
Expand Down Expand Up @@ -103,6 +106,26 @@ public WebserviceHttpClientChannel(final String urlSpec,
setUploadFile(uploadFile);
setFileparam(fileparam);
}
/**
* Creates a new instance of ColonyHttpChannel.
*
* @param urlSpec The base URL for the request
* @param authenticator a ColonyHttpAuthenticator instance
* @param query a Map of query parameters to be added to the URL
* @param uploadFile a file to upload as part of a multipart request
* @param fileparam parameter name for the uploaded file in the multipart request
*
* @throws com.dtolabs.rundeck.core.CoreException
* if the Bean cannot be correctly marshalled via the {@link com.networkgps.itnav.colony.MarshallFacility}.
*/
public WebserviceHttpClientChannel(final String urlSpec,
final HttpAuthenticator authenticator,
final Map query,
final Map<String,String> formData)
throws CoreException {
this(urlSpec, authenticator, query);
setFormData(formData);
}

/**
* Creates a new instance of ColonyHttpChannel.
Expand Down Expand Up @@ -174,8 +197,21 @@ protected RequestEntity getRequestEntity(final PostMethod method) {
}
}

@Override
protected NameValuePair[] getRequestBody(final PostMethod method) {
if(null!=formData && formData.size()>0) {
final ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
for (final Map.Entry<String, String> stringStringEntry : formData.entrySet()) {
list.add(new NameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue()));
}
return list.toArray(new NameValuePair[formData.size()]);
}else{
return null;
}
}

protected boolean isPostMethod() {
return null != uploadFile;
return null != uploadFile || null!=formData && formData.size()>0;
}

/**
Expand Down Expand Up @@ -228,7 +264,7 @@ protected void postMakeRequest() {
validResponse = getResultCode() >= 200 && getResultCode() < 300;
errorResponse = !validResponse;
String type = getResultContentType();
if (type.indexOf(";") > 0) {
if (type!=null && type.indexOf(";") > 0) {
type = type.substring(0, type.indexOf(";")).trim();
}
if (XML_CONTENT_TYPE.equals(type)) {
Expand Down Expand Up @@ -261,4 +297,12 @@ public void setFileparam(final String fileparam) {
private void setResultDoc(final Document resultDoc) {
this.resultDoc = resultDoc;
}

public Map<String, String> getFormData() {
return formData;
}

public void setFormData(Map<String, String> formData) {
this.formData = formData;
}
}
Expand Up @@ -95,6 +95,20 @@ public WebserviceHttpClient getWebserviceHttpClient(final String urlSpec,

}

public WebserviceHttpClient getWebserviceHttpClient(final String urlSpec,
final String basePath,
final String username,
final String password,
final Map query,
final Map<String,String> formData) {

return new WebserviceHttpClientChannel(urlSpec,
new WebserviceFormAuthenticator(basePath, username, password),
query,
formData);

}

public WebserviceHttpClient getWebserviceHttpClient(final String urlSpec,
final String basePath,
final String username,
Expand Down Expand Up @@ -222,5 +236,24 @@ public abstract WebserviceHttpClient getWebserviceHttpClient(String urlSpec,
OutputStream destination,
String expectedContentType);


/**
* Get a WebserviceHttpClient from the parameters.
*
* @param urlSpec URL to request
* @param basePath base context path on the server for the Webservice application
* @param username username to user
* @param password password to use
* @param query query parameters to add to the request
* @param destination an OutputStream to which to write the result data
* @param expectedContentType the content type expected. if the type does not match, no data is written to the
* outputstream. if null, any type is allowed.
*
* @return WebserviceHttpClient instance
*/
public abstract WebserviceHttpClient getWebserviceHttpClient(final String urlSpec,
final String basePath,
final String username,
final String password,
final Map query,
final Map<String, String> formData);
}

0 comments on commit 054d4b2

Please sign in to comment.