use of org.apache.commons.httpclient.HttpMethod in project sling by apache.
the class AuthenticationResponseCodeTest method testPreventLoopIncorrectHttpBasicCredentials.
@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {
// assume http and webdav are on the same host + port
URL url = new URL(HttpTest.HTTP_BASE_URL);
Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
H.getHttpClient().getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);
final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
HttpMethod get = new GetMethod(requestUrl);
get.setRequestHeader("Referer", requestUrl);
get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
int status = H.getHttpClient().executeMethod(get);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}
use of org.apache.commons.httpclient.HttpMethod in project bamboobsc by billchen198318.
the class CxfServerBean method shutdownOrReloadCallOneSystem.
@SuppressWarnings("unchecked")
public static Map<String, Object> shutdownOrReloadCallOneSystem(HttpServletRequest request, String system, String type) throws ServiceException, Exception {
if (StringUtils.isBlank(system) || StringUtils.isBlank(type)) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
String urlStr = ApplicationSiteUtils.getBasePath(system, request) + "config-services?type=" + type + "&value=" + createParamValue();
logger.info("shutdownOrReloadCallSystem , url=" + urlStr);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(urlStr);
client.executeMethod(method);
byte[] responseBody = method.getResponseBody();
if (null == responseBody) {
throw new Exception("no response!");
}
String content = new String(responseBody, Constants.BASE_ENCODING);
logger.info("shutdownOrReloadCallSystem , system=" + system + " , type=" + type + " , response=" + content);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> dataMap = null;
try {
dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class);
} catch (JsonParseException e) {
logger.error(e.getMessage().toString());
} catch (JsonMappingException e) {
logger.error(e.getMessage().toString());
}
if (null == dataMap) {
throw new Exception("response content error!");
}
return dataMap;
}
use of org.apache.commons.httpclient.HttpMethod in project dianping-open-sdk by dianping.
the class DemoApiTool method requestApi.
/**
* 请求API
*
* @param apiUrl
* @param appKey
* @param secret
* @param paramMap
* @return
*/
public static String requestApi(String apiUrl, String appKey, String secret, Map<String, String> paramMap) {
String queryString = getQueryString(appKey, secret, paramMap);
StringBuffer response = new StringBuffer();
HttpClientParams httpConnectionParams = new HttpClientParams();
httpConnectionParams.setConnectionManagerTimeout(1000);
HttpClient client = new HttpClient(httpConnectionParams);
HttpMethod method = new GetMethod(apiUrl);
try {
if (queryString != null && !queryString.isEmpty()) {
// Encode query string with UTF-8
String encodeQuery = URIUtil.encodeQuery(queryString, "UTF-8");
method.setQueryString(encodeQuery);
}
client.executeMethod(method);
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
reader.close();
} catch (URIException e) {
} catch (IOException e) {
} finally {
method.releaseConnection();
}
return response.toString();
}
use of org.apache.commons.httpclient.HttpMethod in project pinot by linkedin.
the class WebHdfsV1Client method uploadSegment.
// This method is based on:
// https://hadoop.apache.org/docs/r1.0.4/webhdfs.html#CREATE
public synchronized boolean uploadSegment(String webHdfsPath, String localFilePath) {
// Step 1: Submit a HTTP PUT request without automatically following
// redirects and without sending the file data.
String firstPutReqString = String.format(WEB_HDFS_UPLOAD_PATH_TEMPLATE, _protocol, _host, _port, webHdfsPath, _overwrite, _permission);
HttpMethod firstPutReq = new PutMethod(firstPutReqString);
try {
LOGGER.info("Trying to send request: {}.", firstPutReqString);
int firstResponseCode = _httpClient.executeMethod(firstPutReq);
if (firstResponseCode != 307) {
LOGGER.error(String.format("Failed to execute the first PUT request to upload segment to webhdfs: %s. " + "Expected response code 307, but get %s. Response body: %s", firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString()));
return false;
}
} catch (Exception e) {
LOGGER.error(String.format("Failed to execute the first request to upload segment to webhdfs: %s.", firstPutReqString), e);
return false;
} finally {
firstPutReq.releaseConnection();
}
// Step 2: Submit another HTTP PUT request using the URL in the Location
// header with the file data to be written.
String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue();
PutMethod redirectedReq = new PutMethod(redirectedReqString);
File localFile = new File(localFilePath);
RequestEntity requestEntity = new FileRequestEntity(localFile, "application/binary");
redirectedReq.setRequestEntity(requestEntity);
try {
LOGGER.info("Trying to send request: {}.", redirectedReqString);
int redirectedResponseCode = _httpClient.executeMethod(redirectedReq);
if (redirectedResponseCode != 201) {
LOGGER.error(String.format("Failed to execute the redirected PUT request to upload segment to webhdfs: %s. " + "Expected response code 201, but get %s. Response: %s", redirectedReqString, redirectedResponseCode, redirectedReq.getResponseBodyAsString()));
}
return true;
} catch (IOException e) {
LOGGER.error(String.format("Failed to execute the redirected request to upload segment to webhdfs: %s.", redirectedReqString), e);
return false;
} finally {
redirectedReq.releaseConnection();
}
}
use of org.apache.commons.httpclient.HttpMethod in project openhab1-addons by openhab.
the class Connection method sendCommand.
/**
* Send a command to the Particle REST API (convenience function).
*
* @param device
* the device context, or <code>null</code> if not needed for this command.
* @param funcName
* the function name to call, or variable/field to retrieve if <code>command</code> is
* <code>null</code>.
* @param user
* the user name to use in Basic Authentication if the funcName would require Basic Authentication.
* @param pass
* the password to use in Basic Authentication if the funcName would require Basic Authentication.
* @param command
* the command to send to the API.
* @param proc
* a callback object that receives the status code and response body, or <code>null</code> if not
* needed.
*/
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
String url = null;
String httpMethod = null;
String content = null;
String contentType = null;
Properties headers = new Properties();
logger.trace("sendCommand: funcName={}", funcName);
switch(funcName) {
case "createToken":
httpMethod = HTTP_POST;
url = TOKEN_URL;
content = command;
contentType = APPLICATION_FORM_URLENCODED;
break;
case "deleteToken":
httpMethod = HTTP_DELETE;
url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
break;
case "getDevices":
httpMethod = HTTP_GET;
url = String.format(GET_DEVICES_URL, tokens.accessToken);
break;
default:
url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
if (command == null) {
// retrieve a variable
httpMethod = HTTP_GET;
} else {
// call a function
httpMethod = HTTP_POST;
content = command;
contentType = APPLICATION_JSON;
}
break;
}
HttpClient client = new HttpClient();
if (!url.contains("access_token=")) {
Credentials credentials = new UsernamePasswordCredentials(user, pass);
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
HttpMethod method = createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : headers.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
}
try {
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && content != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
logger.trace("content='{}', contentType='{}'", content, contentType);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '{}'", method.getURI());
} catch (URIException e) {
logger.debug(e.getMessage());
}
}
int statusCode = client.executeMethod(method);
if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
logger.debug("Method failed: " + method.getStatusLine());
}
String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
if (!responseBody.isEmpty()) {
logger.debug("Body of response: {}", responseBody);
}
if (proc != null) {
proc.handleResponse(statusCode, responseBody);
}
} catch (HttpException he) {
logger.warn("{}", he);
} catch (IOException ioe) {
logger.debug("{}", ioe);
} finally {
method.releaseConnection();
}
}
Aggregations