use of org.apache.commons.httpclient.params.HttpMethodParams in project tdi-studio-se by Talend.
the class HttpMethodBase method recycle.
/**
* Recycles the HTTP method so that it can be used again.
* Note that all of the instance variables will be reset
* once this method has been called. This method will also
* release the connection being used by this HTTP method.
*
* @see #releaseConnection()
*
* @deprecated no longer supported and will be removed in the future
* version of HttpClient
*/
public void recycle() {
LOG.trace("enter HttpMethodBase.recycle()");
releaseConnection();
path = null;
followRedirects = false;
doAuthentication = true;
queryString = null;
getRequestHeaderGroup().clear();
getResponseHeaderGroup().clear();
getResponseTrailerHeaderGroup().clear();
statusLine = null;
effectiveVersion = null;
aborted = false;
used = false;
params = new HttpMethodParams();
responseBody = null;
recoverableExceptionCount = 0;
connectionCloseForced = false;
hostAuthState.invalidate();
proxyAuthState.invalidate();
cookiespec = null;
requestSent = false;
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.
the class SoapHttpTransport method invoke.
public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
PostMethod method = null;
try {
// Assemble post method. Append document name, so that the request
// type is written to the access log.
String uri, query;
int i = mUri.indexOf('?');
if (i >= 0) {
uri = mUri.substring(0, i);
query = mUri.substring(i);
} else {
uri = mUri;
query = "";
}
if (!uri.endsWith("/"))
uri += '/';
uri += getDocumentName(document);
method = new PostMethod(uri + query);
// Set user agent if it's specified.
String agentName = getUserAgentName();
if (agentName != null) {
String agentVersion = getUserAgentVersion();
if (agentVersion != null)
agentName += " " + agentVersion;
method.setRequestHeader(new Header("User-Agent", agentName));
}
// the content-type charset will determine encoding used
// when we set the request body
method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
if (getClientIp() != null) {
method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
if (ZimbraLog.misc.isDebugEnabled()) {
ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
}
}
Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
HttpMethodParams params = method.getParams();
method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
if (getRequestProtocol().hasSOAPActionHeader())
method.setRequestHeader("SOAPAction", mUri);
if (mCustomHeaders != null) {
for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
}
String host = method.getURI().getHost();
HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
String trustedToken = getTrustedToken();
if (trustedToken != null) {
state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
}
params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
params.setSoTimeout(mTimeout);
params.setVersion(HttpVersion.HTTP_1_1);
method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
}
if (mHttpDebugListener != null) {
mHttpDebugListener.sendSoapMessage(method, soapReq, state);
}
int responseCode = mClient.executeMethod(mHostConfig, method, state);
// real server issues will probably be "503" or "404"
if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
// Read the response body. Use the stream API instead of the byte[]
// version to avoid HTTPClient whining about a large response.
InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
String responseStr = "";
try {
if (respHandler != null) {
respHandler.process(reader);
return null;
} else {
responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
Element soapResp = parseSoapResponse(responseStr, raw);
if (mHttpDebugListener != null) {
mHttpDebugListener.receiveSoapMessage(method, soapResp);
}
return soapResp;
}
} catch (SoapFaultException x) {
// attach request/response to the exception and rethrow
x.setFaultRequest(soapMessage);
x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
throw x;
}
} finally {
// Release the connection to the connection manager
if (method != null)
method.releaseConnection();
// exits. Leave it here anyway.
if (!mKeepAlive)
mClient.getHttpConnectionManager().closeIdleConnections(0);
}
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.
the class WebDavClient method executeMethod.
protected HttpMethod executeMethod(HttpMethod m, Depth d, String bodyForLogging) throws IOException {
HttpMethodParams p = m.getParams();
if (p != null)
p.setCredentialCharset("UTF-8");
m.setDoAuthentication(true);
m.setRequestHeader("User-Agent", mUserAgent);
String depth = "0";
switch(d) {
case one:
depth = "1";
break;
case infinity:
depth = "infinity";
break;
case zero:
break;
default:
break;
}
m.setRequestHeader("Depth", depth);
logRequestInfo(m, bodyForLogging);
HttpClientUtil.executeMethod(mClient, m);
logResponseInfo(m);
return m;
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.
the class TestProvIDN method testBasicAuth.
@Test
public void testBasicAuth() throws Exception {
Names.IDNName domainName = new Names.IDNName(makeTestDomainName("basicAuthTest."));
Domain domain = createDomain(domainName.uName(), domainName.uName());
Names.IDNName acctName = new Names.IDNName("acct", domainName.uName());
Account acct = (Account) createTest(EntryType.ACCOUNT, NameType.UNAME, acctName);
HttpState initialState = new HttpState();
/*
Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false);
Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false);
initialState.addCookie(authCookie);
initialState.addCookie(sessionCookie);
*/
String guestName = acct.getUnicodeName();
String guestPassword = "test123";
Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
initialState.setCredentials(AuthScope.ANY, loginCredentials);
HttpClient client = new HttpClient();
client.setState(initialState);
String url = UserServlet.getRestUrl(acct) + "/Calendar";
System.out.println("REST URL: " + url);
HttpMethod method = new GetMethod(url);
HttpMethodParams methodParams = method.getParams();
methodParams.setCredentialCharset("UTF-8");
try {
int respCode = HttpClientUtil.executeMethod(client, method);
if (respCode != HttpStatus.SC_OK) {
System.out.println("failed, respCode=" + respCode);
} else {
boolean chunked = false;
boolean textContent = false;
/*
System.out.println("Headers:");
System.out.println("--------");
for (Header header : method.getRequestHeaders()) {
System.out.print(" " + header.toString());
}
System.out.println();
System.out.println("Body:");
System.out.println("-----");
String respBody = method.getResponseBodyAsString();
System.out.println(respBody);
*/
}
} finally {
// Release the connection.
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.params.HttpMethodParams in project pinot by linkedin.
the class ServerSegmentCompletionProtocolHandler method doHttp.
private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) {
SegmentCompletionProtocol.Response response = SegmentCompletionProtocol.RESP_NOT_SENT;
HttpClient httpClient = new HttpClient();
ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance();
final String leaderAddress = leaderLocator.getControllerLeader();
if (leaderAddress == null) {
LOGGER.error("No leader found {}", this.toString());
return SegmentCompletionProtocol.RESP_NOT_LEADER;
}
final String url = request.getUrl(leaderAddress);
HttpMethodBase method;
if (parts != null) {
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
method = postMethod;
} else {
method = new GetMethod(url);
}
LOGGER.info("Sending request {} for {}", url, this.toString());
try {
int responseCode = httpClient.executeMethod(method);
if (responseCode >= 300) {
LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString());
return response;
} else {
response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString());
LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString());
if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) {
leaderLocator.refreshControllerLeader();
}
return response;
}
} catch (IOException e) {
LOGGER.error("IOException {}", this.toString(), e);
leaderLocator.refreshControllerLeader();
return response;
}
}
Aggregations