下面列出了怎么用org.apache.commons.httpclient.HttpMethodBase的API类实例代码及写法,或者点击链接到github查看源代码。
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
if ("GET".equals(method))
{
return new GetMethod(url);
}
if ("POST".equals(method))
{
return new PostMethod(url);
}
if ("PUT".equals(method))
{
return new PutMethod(url);
}
if ("DELETE".equals(method))
{
return new DeleteMethod(url);
}
if (TestingMethod.METHOD_NAME.equals(method))
{
return new TestingMethod(url);
}
throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
private static String getHeaders(HttpMethodBase method) {
Header[] headersArray = method.getRequestHeaders();
Map<String, String> headers = new HashMap<>(headersArray.length);
for (int i = 0; i < headersArray.length; i++) { // only 1 value admitted for each header
headers.put(headersArray[i].getName(), headersArray[i].getValue());
}
StringBuilder res = new StringBuilder();
for (String name : HMACUtils.HEADERS_SIGNED) {
String value = headers.get(name); // only 1 value admitted
if (value != null) {
res.append(name);
res.append(value);
}
}
return res.toString();
}
private static HttpMethodBase getMethod(HttpMethod method, String address) {
String addr = address;
if (method.equals(HttpMethod.Delete)) {
return new DeleteMethod(addr);
}
if (method.equals(HttpMethod.Post)) {
return new PostMethod(addr);
}
if (method.equals(HttpMethod.Get)) {
return new GetMethod(addr);
}
if (method.equals(HttpMethod.Put)) {
return new PutMethod(addr);
}
Assert.assertUnreachable("method doesn't exist");
return null;
}
/**
* Builds a new Request object, using HttpClient method descriptions
*/
public RemoteConnectorRequest buildRequest(String url, Class<? extends HttpMethodBase> method)
{
// Get the method name
String methodName;
try
{
HttpMethodBase httpMethod = method.getConstructor(String.class).newInstance(url);
methodName = httpMethod.getName();
}
catch(Exception e)
{
throw new AlfrescoRuntimeException("Error identifying method name", e);
}
// Build and return
return buildRequest(url, methodName);
}
public String getResponse()
{
if (responseBytes != null)
{
if (method instanceof HttpMethodBase)
{
// mimic method.getResponseBodyAsString
return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
}
else
{
return new String(responseBytes);
}
}
else
{
return null;
}
}
private void overrideHeaders(HttpMethodBase httpMethod, String url,
String method) {
String headers = getRequestHeaders();
String[] header = headers.split(System.getProperty("line.separator"));
for (String kvp : header) {
int pos = kvp.indexOf(':');
if (pos < 0) {
pos = kvp.indexOf('=');
}
if (pos > 0) {
String k = kvp.substring(0, pos).trim();
String v = "";
if (kvp.length() > pos + 1) {
v = kvp.substring(pos + 1).trim();
}
httpMethod.addRequestHeader(k, v);
}
}
String authorization = OAuthGenerator.getInstance(getConsumerKey(),
getConsumerSecret()).getAuthorization(url, method);
httpMethod.addRequestHeader("Authorization", authorization);
}
/**
* adding OAuth authorization headers to a httpMethod
*
* @param httpMethod method which wants to add Authorization header
*/
private void setAuthorizationHeader(HttpMethodBase httpMethod)
throws IdentityProvisioningException {
boolean isDebugEnabled = log.isDebugEnabled();
String accessToken = authenticate();
if (StringUtils.isNotBlank(accessToken)) {
httpMethod.setRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME,
SalesforceConnectorConstants.AUTHORIZATION_HEADER_OAUTH + " " + accessToken);
if (isDebugEnabled) {
log.debug("Setting authorization header for method : " + httpMethod.getName()
+ " as follows,");
Header authorizationHeader = httpMethod
.getRequestHeader(SalesforceConnectorConstants.AUTHORIZATION_HEADER_NAME);
log.debug(authorizationHeader.getName() + ": " + authorizationHeader.getValue());
}
} else {
throw new IdentityProvisioningException("Authentication failed");
}
}
private String responseToErrorMessage(final HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
if ("text/html".equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
// The error message is the response content
// Safety margin of 2048 characters, anything longer is probably useless
// and will clutter the logs
try {
return method.getResponseBodyAsString(2048);
} catch (IOException e) {
S_LOGGER.debug("Error while loading response body", e);
}
}
// The default
return method.getStatusText();
}
private String responseToErrorMessage(final HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
final Header contentTypeHeader = method.getResponseHeader(CONTENT_TYPE);
if (contentTypeHeader != null && TEXT_HTML_CONTENT_TYPE.equals(contentTypeHeader.getValue())) {
// The error message is the response content
// Safety margin of 1024 characters, anything longer is probably
// useless and will clutter the logs
try {
return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
} catch (IOException e) {
s_logger.debug("Error while loading response body", e);
}
}
// The default
return method.getStatusText();
}
protected String executeMethod(HttpMethodBase method) throws ApiResultException {
try {
log.info("executing method:" + method);
int responseCode = httpClient.executeMethod(method);
String responseBody = method.getResponseBodyAsString();
if (responseBody != null && !responseBody.isEmpty()) {
return responseBody;
} else {
StringBuilder buffer = new StringBuilder();
buffer.append("No response body was returned!\nResponse Headers-\n");
Header[] headers = method.getResponseHeaders();
for (Header header : headers) {
buffer.append(header.getName()).append(": ").append(header.getValue()).append("\n");
}
buffer.append("HTTP-Response-Code: ").append(responseCode).append("\n");
buffer.append("Content length reported as: ").append(method.getResponseContentLength());
log.info(buffer.toString());
throw new ApiResultException("Error executing API: " + buffer.toString(), new NoResponseApiErrorResult());
}
} catch(IOException e) {
throw new ApiException("Error executing API: ", e);
}
}
protected static HttpMethodBase buildHttpClientMethod(String url, Class<? extends HttpMethodBase> method)
{
HttpMethodBase request = null;
try
{
request = method.getConstructor(String.class).newInstance(url);
}
catch(Exception e)
{
throw new AlfrescoRuntimeException("HttpClient broken", e);
}
return request;
}
/**
*
* @param method
* @throws HMACSecurityException
*/
public void provideAuthentication(HttpMethodBase method, String body) throws HMACSecurityException {
String token = validator.generateToken();
Assert.assertNotNull(token, "token");
String signature;
try {
signature = getSignature(method, body, token);
} catch (Exception e) {
throw new HMACSecurityException("Problems while signing the request", e);
}
method.addRequestHeader(HMACUtils.HMAC_TOKEN_HEADER, token);
method.addRequestHeader(HMACUtils.HMAC_SIGNATURE_HEADER, signature);
}
/**
* Add the headers to the method, and the auth token (which must be set
* @param method method to update
* @param requestHeaders the list of headers
* @throws SwiftInternalStateException not yet authenticated
*/
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
throws SwiftInternalStateException {
for (Header header : requestHeaders) {
method.addRequestHeader(header);
}
setAuthToken(method, getToken());
}
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception {
InputStream in = null;
try {
method.addRequestHeader("Connection", "close");
HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
//设置连接时候一些参数
params.setConnectionTimeout(timeout);
params.setSoTimeout(timeout);
params.setStaleCheckingEnabled(false);
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);
int stat = client.executeMethod(method);
if (stat != HttpStatus.SC_OK)
log.error("get失败!");
//method.getResponseBody()
in = method.getResponseBodyAsStream();
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
finally {
if (in != null) {
in.close();
}
}
}
/**
* Add the headers to the method, and the auth token (which must be set
* @param method method to update
* @param requestHeaders the list of headers
* @throws SwiftInternalStateException not yet authenticated
*/
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
throws SwiftInternalStateException {
for (Header header : requestHeaders) {
method.addRequestHeader(header);
}
setAuthToken(method, getToken());
}
private static void copyHttpMethodBase(
HttpMethodBase m, HttpMethodBase copy) {
try {
copy.setParams((HttpMethodParams)m.getParams().clone());
} catch (CloneNotSupportedException e) {
// Should never happen
}
}
/**
* Will create the method and execute it. After this the method is sent to a
* ResponseHandler that is returned.
*
* @param httpRequest
* Request we are receiving from the client
* @param url
* The location we are proxying to
* @return A ResponseHandler that can be used to write the response
* @throws MethodNotAllowedException
* If the method specified by the request isn't handled
* @throws IOException
* When there is a problem with the streams
* @throws HttpException
* The httpclient can throw HttpExcetion when executing the
* method
*/
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
throws MethodNotAllowedException, IOException, HttpException {
RequestHandler requestHandler = RequestHandlerFactory
.createRequestMethod(httpRequest.getMethod());
HttpMethod method = requestHandler.process(httpRequest, url);
method.setFollowRedirects(false);
/*
* Why does method.validate() return true when the method has been
* aborted? I mean, if validate returns true the API says that means
* that the method is ready to be executed. TODO I don't like doing type
* casting here, see above.
*/
if (!((HttpMethodBase) method).isAborted()) {
httpClient.executeMethod(method);
if (method.getStatusCode() == 405) {
Header allow = method.getResponseHeader("allow");
String value = allow.getValue();
throw new MethodNotAllowedException(
"Status code 405 from server",
AllowedMethodHandler.processAllowHeader(value));
}
}
return ResponseHandlerFactory.createResponseHandler(method);
}
/**
* Add the headers to the method, and the auth token (which must be set
* @param method method to update
* @param requestHeaders the list of headers
* @throws SwiftInternalStateException not yet authenticated
*/
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
throws SwiftInternalStateException {
for (Header header : requestHeaders) {
method.addRequestHeader(header);
}
setAuthToken(method, getToken());
}
private void parseHtml(HttpMethodBase httpMethod, String response) {
// parse the html of what we have found
Header contentType = httpMethod.getResponseHeader("Content-Type");
if (contentType != null) {
if (contentType.getValue().startsWith("text")) {
manager.addHTMLToParseQueue(new HTMLparseWorkUnit(response, work));
}
}
}
private Charset getCharsetFrom(HttpMethodBase httpMethod) {
Charset chartSet;
try {
chartSet = Charset.forName(httpMethod.getRequestCharSet());
} catch (Exception ex) {
chartSet = Charset.forName("UTF-8");
}
return chartSet;
}
private String getHeadersAsString(HttpMethodBase httpMethod) {
Header[] headers = httpMethod.getResponseHeaders();
StringBuilder builder = new StringBuilder(20 * (headers.length + 1));
builder.append(httpMethod.getStatusLine());
builder.append("\r\n");
for (Header header : headers) {
builder.append(header.getName()).append(": ").append(header.getValue());
builder.append("\r\n");
}
return builder.append("\r\n").toString();
}
private HttpMethodBase createHttpMethod(String method, String urlStr) {
HttpMethodBase httpMethod;
// May generate IllegalArgumentException
if (method.equals(HTTPConstantsInterface.POST)) {
httpMethod = new PostMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.PUT)) {
httpMethod = new PutMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.HEAD)) {
httpMethod = new HeadMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.TRACE)) {
httpMethod = new TraceMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.OPTIONS)) {
httpMethod = new OptionsMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.DELETE)) {
httpMethod = new DeleteMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.GET)) {
httpMethod = new GetMethod(urlStr);
} else if (method.equals(HTTPConstantsInterface.PATCH)) {
httpMethod = new PutMethod(urlStr) {
@Override
public String getName() {
return "PATCH";
}
};
} else {
log.error("Unexpected method (converted to GET): " + method);
httpMethod = new GetMethod(urlStr);
}
return httpMethod;
}
private void executeHttpMethod(@NotNull HttpMethodBase method) throws IOException {
adjustHttpHeader(method);
final HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)
client.executeMethod(method);
}
public static Header[] printResponseHeaders(HttpMethodBase httpget) throws IOException {
System.out.println("Printing Response Header...\n");
Header[] headers = httpget.getResponseHeaders();
for (Header header : headers) {
System.out.println("Key : " + header.getName()
+ " ,Value : " + header.getValue());
}
return headers;
}
private String checkResponse(final HttpMethodBase m, final String errorMessageBase) throws BigSwitchBcfApiException,
IllegalArgumentException{
String customErrorMsg = null;
if (m.getStatusCode() == HttpStatus.SC_OK) {
String hash = "";
if (m.getResponseHeader(HASH_MATCH) != null) {
hash = m.getResponseHeader(HASH_MATCH).getValue();
set_hash(hash);
}
return hash;
}
if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
if(m instanceof GetMethod) {
return HASH_CONFLICT;
}
throw new BigSwitchBcfApiException("BCF topology sync required", true);
}
if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
isMaster = false;
set_hash(HASH_IGNORE);
return HASH_IGNORE;
}
if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
if (m instanceof DeleteMethod){
return "";
}
}
if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
customErrorMsg = " Invalid data in BCF request";
throw new IllegalArgumentException(customErrorMsg);
}
String errorMessage = responseToErrorMessage(m);
m.releaseConnection();
S_LOGGER.error(errorMessageBase + errorMessage);
throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}
private void setHttpHeader(final HttpMethodBase m) {
m.setRequestHeader(CONTENT_TYPE, CONTENT_JSON);
m.setRequestHeader(ACCEPT, CONTENT_JSON);
m.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID + "-" + zoneId);
if (StringUtils.isNotEmpty(hash)) {
m.setRequestHeader(HASH_MATCH, hash);
}
String authString = username + ":" + password;
String encodedAuthString = "Basic " + Base64.encodeBase64String(authString.getBytes(Charset.forName("UTF-8")));
m.setRequestHeader("Authorization", encodedAuthString);
}
@Test
public void testExecuteRetrieveControllerMasterStatus() throws BigSwitchBcfApiException, IOException {
_method = mock(GetMethod.class);
when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(((HttpMethodBase)_method).getResponseBodyAsString(2048)).thenReturn("{'healthy': true, 'topologySyncRequested': false}");
_api.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
}.getType(), "/", null);
verify(_method, times(1)).releaseConnection();
verify(_client, times(1)).executeMethod(_method);
assertEquals(_api.getControllerData().isMaster(), true);
}
@Test
public void testExecuteRetrieveControllerMasterStatusWithTopoConflict() throws BigSwitchBcfApiException, IOException {
_method = mock(GetMethod.class);
when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CONFLICT);
when(((HttpMethodBase)_method).getResponseBodyAsString(2048)).thenReturn("{'healthy': true, 'topologySyncRequested': true}");
_api.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
}.getType(), "/", null);
verify(_method, times(1)).releaseConnection();
verify(_client, times(1)).executeMethod(_method);
assertEquals(_api.getControllerData().isMaster(), true);
}
@Test
public void testExecuteRetrieveControllerSlaveStatus() throws BigSwitchBcfApiException, IOException {
_method = mock(GetMethod.class);
when(_method.getStatusCode()).thenReturn(HttpStatus.SC_SEE_OTHER);
when(((HttpMethodBase)_method).getResponseBodyAsString(1024)).thenReturn("{'healthy': true, 'topologySyncRequested': false}");
_api.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
}.getType(), "/", null);
verify(_method, times(1)).releaseConnection();
verify(_client, times(1)).executeMethod(_method);
assertEquals(_api.getControllerData().isMaster(), false);
}
protected NeutronRestApi(final Class<? extends HttpMethodBase> httpClazz, final String protocol, final int port) {
client = createHttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
this.httpClazz = httpClazz;
try {
// Cast to ProtocolSocketFactory to avoid the deprecated constructor
// with the SecureProtocolSocketFactory parameter
Protocol.registerProtocol(protocol, new Protocol(protocol, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
} catch (IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
}