Search in sources :

Example 76 with HttpMethod

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);
}
Also used : AuthScope(org.apache.commons.httpclient.auth.AuthScope) GetMethod(org.apache.commons.httpclient.methods.GetMethod) URL(java.net.URL) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) HttpTest(org.apache.sling.commons.testing.integration.HttpTest) Test(org.junit.Test)

Example 77 with HttpMethod

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;
}
Also used : ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) HttpClient(org.apache.commons.httpclient.HttpClient) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JsonParseException(com.fasterxml.jackson.core.JsonParseException) HttpMethod(org.apache.commons.httpclient.HttpMethod) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 78 with HttpMethod

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();
}
Also used : URIException(org.apache.commons.httpclient.URIException) InputStreamReader(java.io.InputStreamReader) HttpClient(org.apache.commons.httpclient.HttpClient) HttpClientParams(org.apache.commons.httpclient.params.HttpClientParams) GetMethod(org.apache.commons.httpclient.methods.GetMethod) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 79 with HttpMethod

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();
    }
}
Also used : FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) PutMethod(org.apache.commons.httpclient.methods.PutMethod) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) File(java.io.File) HttpMethod(org.apache.commons.httpclient.HttpMethod) IOException(java.io.IOException)

Example 80 with HttpMethod

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();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

HttpMethod (org.apache.commons.httpclient.HttpMethod)151 HttpClient (org.apache.commons.httpclient.HttpClient)99 GetMethod (org.apache.commons.httpclient.methods.GetMethod)95 InputStream (java.io.InputStream)61 IOException (java.io.IOException)43 ArrayList (java.util.ArrayList)30 HttpException (org.apache.commons.httpclient.HttpException)28 Map (java.util.Map)24 Test (org.junit.Test)23 Element (org.w3c.dom.Element)22 HashMap (java.util.HashMap)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 Header (org.apache.commons.httpclient.Header)17 List (java.util.List)14 NameValuePair (org.apache.commons.httpclient.NameValuePair)13 NodeList (org.w3c.dom.NodeList)12 FileInputStream (java.io.FileInputStream)10 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)10 SAXBuilder (org.jdom.input.SAXBuilder)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9