下面列出了怎么用org.apache.commons.httpclient.methods.EntityEnclosingMethod的API类实例代码及写法,或者点击链接到github查看源代码。
private void sendRequest() throws IOException {
synchronized(lock) {
if (out != null) {
if (!(resCache instanceof EntityEnclosingMethod)) {
System.err.println("Warning: data written to request's body, "
+"but not supported");
} else {
EntityEnclosingMethod m = (EntityEnclosingMethod) resCache;
m.setRequestEntity(new ByteArrayRequestEntity(out.getBytes()));
}
}
client.executeMethod(resCache);
requestSent = true;
}
}
/**
* Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
* as was sent in the given {@link HttpServletRequest}
*
* @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
* multipart POST request
* @param httpServletRequest The {@link HttpServletRequest} that contains the multipart
* POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
*/
@SuppressWarnings("unchecked")
public static void handleMultipartPost(
EntityEnclosingMethod postMethodProxyRequest,
HttpServletRequest httpServletRequest,
DiskFileItemFactory diskFileItemFactory)
throws ServletException {
// TODO: this function doesn't set any history data
try {
// just pass back the binary data
InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream());
postMethodProxyRequest.setRequestEntity(ire);
postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME));
} catch (Exception e) {
throw new ServletException(e);
}
}
/**
* Adds the JSON as request-body the the method and sets the correct
* content-type.
* @param method EntityEnclosingMethod
* @param object JSONObject
*/
private void populateRequestBody(EntityEnclosingMethod method, JSONObject object)
{
try
{
method.setRequestEntity(new StringRequestEntity(object.toJSONString(), MIME_TYPE_JSON, "UTF-8"));
}
catch (UnsupportedEncodingException error)
{
// This will never happen!
throw new RuntimeException("All hell broke loose, a JVM that doesn't have UTF-8 encoding...");
}
}
void sendMessageWithCustomHostHeader(HttpMessage message, String host) throws IOException {
HttpMethodParams params = new HttpMethodParams();
params.setVirtualHost(host);
HttpMethod method =
createRequestMethod(message.getRequestHeader(), message.getRequestBody(), params);
if (!(method instanceof EntityEnclosingMethod) || method instanceof ZapGetMethod) {
method.setFollowRedirects(false);
}
User forceUser = getParent().getHttpSender().getUser(message);
message.setTimeSentMillis(System.currentTimeMillis());
if (forceUser != null) {
getParent()
.getHttpSender()
.executeMethod(method, forceUser.getCorrespondingHttpState());
} else {
getParent().getHttpSender().executeMethod(method, null);
}
message.setTimeElapsedMillis(
(int) (System.currentTimeMillis() - message.getTimeSentMillis()));
HttpMethodHelper.updateHttpRequestHeaderSent(message.getRequestHeader(), method);
HttpResponseHeader resHeader = HttpMethodHelper.getHttpResponseHeader(method);
resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null);
message.setResponseHeader(resHeader);
message.getResponseBody().setCharset(resHeader.getCharset());
message.getResponseBody().setLength(0);
message.getResponseBody().append(method.getResponseBody());
message.setResponseFromTargetHost(true);
getParent().notifyNewMessage(this, message);
}
private static HttpMethod createRequestMethod(
HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException {
HttpMethod httpMethod = new ZapGetMethod();
httpMethod.setURI(header.getURI());
httpMethod.setParams(params);
params.setVersion(HttpVersion.HTTP_1_1);
String msg = header.getHeadersAsString();
String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg);
String token = null;
String name = null;
String value = null;
int pos = 0;
for (int i = 0; i < split.length; i++) {
token = split[i];
if (token.equals("")) {
continue;
}
if ((pos = token.indexOf(":")) < 0) {
return null;
}
name = token.substring(0, pos).trim();
value = token.substring(pos + 1).trim();
httpMethod.addRequestHeader(name, value);
}
if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
}
httpMethod.setFollowRedirects(false);
return httpMethod;
}
@Override
public String getEntity(HttpMethod httpMethod) {
if (httpMethod instanceof EntityEnclosingMethod) {
final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
try {
String entityValue;
String charSet = entityEnclosingMethod.getRequestCharSet();
if (StringUtils.isEmpty(charSet)) {
charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
}
if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
entityValue = entityUtilsToString(entity, charSet);
} else {
entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
}
return entityValue;
} catch (Exception e) {
if (isDebug) {
logger.debug("Failed to get entity. httpMethod={}", httpMethod, e);
}
}
}
}
return null;
}
/**
* Update entry by posting new representation of entry to server. Note that you should not
* attempt to update entries that you get from iterating over a collection they may be "partial"
* entries. If you want to update an entry, you must get it via one of the
* <code>getEntry()</code> methods in {@link com.rometools.rome.propono.atom.common.Collection}
* or {@link com.rometools.rome.propono.atom.common.AtomService}.
*
* @throws ProponoException If entry is a "partial" entry.
*/
public void update() throws ProponoException {
if (partial) {
throw new ProponoException("ERROR: attempt to update partial entry");
}
final EntityEnclosingMethod method = new PutMethod(getEditURI());
addAuthentication(method);
final StringWriter sw = new StringWriter();
final int code = -1;
try {
Atom10Generator.serializeEntry(this, sw);
method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
getHttpClient().executeMethod(method);
final InputStream is = method.getResponseBodyAsStream();
if (method.getStatusCode() != 200 && method.getStatusCode() != 201) {
throw new ProponoException("ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
}
} catch (final Exception e) {
final String msg = "ERROR: updating entry, HTTP code: " + code;
LOG.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
}
}
void addToCollection(final ClientCollection col) throws ProponoException {
setCollection(col);
final EntityEnclosingMethod method = new PostMethod(getCollection().getHrefResolved());
addAuthentication(method);
final StringWriter sw = new StringWriter();
int code = -1;
try {
Atom10Generator.serializeEntry(this, sw);
method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
getHttpClient().executeMethod(method);
final InputStream is = method.getResponseBodyAsStream();
code = method.getStatusCode();
if (code != 200 && code != 201) {
throw new ProponoException("ERROR HTTP status=" + code + " : " + Utilities.streamToString(is));
}
final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), getCollection().getHrefResolved(), Locale.US);
BeanUtils.copyProperties(this, romeEntry);
} catch (final Exception e) {
final String msg = "ERROR: saving entry, HTTP code: " + code;
LOG.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
}
final Header locationHeader = method.getResponseHeader("Location");
if (locationHeader == null) {
LOG.warn("WARNING added entry, but no location header returned");
} else if (getEditURI() == null) {
final List<Link> links = getOtherLinks();
final Link link = new Link();
link.setHref(locationHeader.getValue());
link.setRel("edit");
links.add(link);
setOtherLinks(links);
}
}
@SuppressWarnings("deprecation")
public static Response makeRequest(HttpMethod httpMethod, String address, Map<String, String> requestHeaders, String requestBody,
List<NameValuePair> queryParams, boolean authenticate) throws HttpException, IOException, HMACSecurityException {
logger.debug("httpMethod = " + httpMethod);
logger.debug("address = " + address);
logger.debug("requestHeaders = " + requestHeaders);
logger.debug("requestBody = " + requestBody);
HttpMethodBase method = getMethod(httpMethod, address);
if (requestHeaders != null) {
for (Entry<String, String> entry : requestHeaders.entrySet()) {
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
if (queryParams != null) {
// add uri query params to provided query params present in query
List<NameValuePair> addressPairs = getAddressPairs(address);
List<NameValuePair> totalPairs = new ArrayList<NameValuePair>(addressPairs);
totalPairs.addAll(queryParams);
method.setQueryString(totalPairs.toArray(new NameValuePair[queryParams.size()]));
}
if (method instanceof EntityEnclosingMethod) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
// charset of request currently not used
eem.setRequestBody(requestBody);
}
if (authenticate) {
String hmacKey = SpagoBIUtilities.getHmacKey();
if (hmacKey != null && !hmacKey.isEmpty()) {
logger.debug("HMAC key found with value [" + hmacKey + "]. Requests will be authenticated.");
HMACFilterAuthenticationProvider authenticationProvider = new HMACFilterAuthenticationProvider(hmacKey);
authenticationProvider.provideAuthentication(method, requestBody);
} else {
throw new SpagoBIRuntimeException("The request need to be authenticated, but hmacKey wasn't found.");
}
}
try {
HttpClient client = getHttpClient(address);
int statusCode = client.executeMethod(method);
Header[] headers = method.getResponseHeaders();
String res = method.getResponseBodyAsString();
return new Response(res, statusCode, headers);
} finally {
method.releaseConnection();
}
}
@SuppressWarnings("deprecation")
public static InputStream makeRequestGetStream(HttpMethod httpMethod, String address, Map<String, String> requestHeaders, String requestBody,
List<NameValuePair> queryParams, boolean authenticate) throws HttpException, IOException, HMACSecurityException {
final HttpMethodBase method = getMethod(httpMethod, address);
if (requestHeaders != null) {
for (Entry<String, String> entry : requestHeaders.entrySet()) {
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
if (queryParams != null) {
// add uri query params to provided query params present in query
List<NameValuePair> addressPairs = getAddressPairs(address);
List<NameValuePair> totalPairs = new ArrayList<NameValuePair>(addressPairs);
totalPairs.addAll(queryParams);
method.setQueryString(totalPairs.toArray(new NameValuePair[queryParams.size()]));
}
if (method instanceof EntityEnclosingMethod) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
// charset of request currently not used
eem.setRequestBody(requestBody);
}
if (authenticate) {
String hmacKey = SpagoBIUtilities.getHmacKey();
if (hmacKey != null && !hmacKey.isEmpty()) {
logger.debug("HMAC key found with value [" + hmacKey + "]. Requests will be authenticated.");
HMACFilterAuthenticationProvider authenticationProvider = new HMACFilterAuthenticationProvider(hmacKey);
authenticationProvider.provideAuthentication(method, requestBody);
} else {
throw new SpagoBIRuntimeException("The request need to be authenticated, but hmacKey wasn't found.");
}
}
HttpClient client = getHttpClient(address);
int statusCode = client.executeMethod(method);
logger.debug("Status code " + statusCode);
Header[] headers = method.getResponseHeaders();
logger.debug("Response header " + headers);
Asserts.check(statusCode == HttpStatus.SC_OK, "Response not OK.\nStatus code: " + statusCode);
return new FilterInputStream(method.getResponseBodyAsStream()) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
method.releaseConnection();
}
}
};
}
private static void copyEntityEnclosingMethod(
EntityEnclosingMethod m, EntityEnclosingMethod copy )
throws java.io.IOException
{
copy.setRequestEntity(m.getRequestEntity());
}
/** Package access, to be called by DefaultClientCollection */
@Override
void addToCollection(final ClientCollection col) throws ProponoException {
setCollection(col);
final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved());
getCollection().addAuthentication(method);
try {
final Content c = getContents().get(0);
if (inputStream != null) {
method.setRequestEntity(new InputStreamRequestEntity(inputStream));
} else {
method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes())));
}
method.setRequestHeader("Content-type", c.getType());
method.setRequestHeader("Title", getTitle());
method.setRequestHeader("Slug", getSlug());
getCollection().getHttpClient().executeMethod(method);
if (inputStream != null) {
inputStream.close();
}
final InputStream is = method.getResponseBodyAsStream();
if (method.getStatusCode() == 200 || method.getStatusCode() == 201) {
final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), col.getHrefResolved(), Locale.US);
BeanUtils.copyProperties(this, romeEntry);
} else {
throw new ProponoException("ERROR HTTP status-code=" + method.getStatusCode() + " status-line: " + method.getStatusLine());
}
} catch (final IOException ie) {
throw new ProponoException("ERROR: saving media entry", ie);
} catch (final JDOMException je) {
throw new ProponoException("ERROR: saving media entry", je);
} catch (final FeedException fe) {
throw new ProponoException("ERROR: saving media entry", fe);
} catch (final IllegalAccessException ae) {
throw new ProponoException("ERROR: saving media entry", ae);
} catch (final InvocationTargetException te) {
throw new ProponoException("ERROR: saving media entry", te);
}
final Header locationHeader = method.getResponseHeader("Location");
if (locationHeader == null) {
LOG.warn("WARNING added entry, but no location header returned");
} else if (getEditURI() == null) {
final List<Link> links = getOtherLinks();
final Link link = new Link();
link.setHref(locationHeader.getValue());
link.setRel("edit");
links.add(link);
setOtherLinks(links);
}
}
/**
* Executes the given <code>url</code> with the given <code>httpMethod</code>
*
* @param httpMethod the HTTP method to use
* @param url the url to execute (in milliseconds)
* @param httpHeaders optional HTTP headers which has to be set on request
* @param content the content to be send to the given <code>url</code> or
* <code>null</code> if no content should be send.
* @param contentType the content type of the given <code>content</code>
* @param timeout the socket timeout to wait for data
* @param proxyHost the hostname of the proxy
* @param proxyPort the port of the proxy
* @param proxyUser the username to authenticate with the proxy
* @param proxyPassword the password to authenticate with the proxy
* @param nonProxyHosts the hosts that won't be routed through the proxy
* @return the response body or <code>NULL</code> when the request went wrong
*/
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
String proxyPassword, String nonProxyHosts) {
HttpClient client = new HttpClient();
// only configure a proxy if a host is provided
if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
client.getHostConfiguration().setProxy(proxyHost, proxyPort);
if (StringUtils.isNotBlank(proxyUser)) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxyUser, proxyPassword));
}
}
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
if (httpHeaders != null) {
for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
}
}
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && content != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
}
Credentials credentials = extractCredentials(url);
if (credentials != null) {
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '{}'", method.getURI());
} catch (URIException e) {
logger.debug("{}", e.getMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.debug("Method failed: {}", method.getStatusLine());
}
String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
if (!responseBody.isEmpty()) {
logger.debug("{}", responseBody);
}
return responseBody;
} catch (HttpException he) {
logger.error("Fatal protocol violation: {}", he.toString());
} catch (IOException ioe) {
logger.error("Fatal transport error: {}", ioe.toString());
} finally {
method.releaseConnection();
}
return null;
}