Search in sources :

Example 46 with Header

use of org.apache.commons.httpclient.Header in project zeppelin by apache.

the class AbstractTestRestApi method getCookie.

private static String getCookie(String user, String password) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url + "/login");
    postMethod.addRequestHeader("Origin", url);
    postMethod.setParameter("password", password);
    postMethod.setParameter("userName", user);
    httpClient.executeMethod(postMethod);
    LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
    Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)");
    Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie");
    for (Header setCookie : setCookieHeaders) {
        java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString());
        if (matcher.find()) {
            return matcher.group(1);
        }
    }
    return StringUtils.EMPTY;
}
Also used : Pattern(java.util.regex.Pattern) Header(org.apache.commons.httpclient.Header) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient)

Example 47 with Header

use of org.apache.commons.httpclient.Header in project twitter-2-weibo by rjyo.

the class HttpClient method httpRequest.

public Response httpRequest(HttpMethod method, Boolean WithTokenHeader) throws WeiboException {
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        List<Header> headers = new ArrayList<Header>();
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            headers.add(new Header("Authorization", "OAuth2 " + token));
            headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress()));
            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
            for (Header hd : headers) {
                log(hd.getName() + ": " + hd.getValue());
            }
        }
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        client.executeMethod(method);
        Header[] resHeader = method.getResponseHeaders();
        responseCode = method.getStatusCode();
        log("Response:");
        log("https StatusCode:" + String.valueOf(responseCode));
        for (Header header : resHeader) {
            log(header.getName() + ":" + header.getValue());
        }
        Response response = new Response();
        response.setResponseAsString(method.getResponseBodyAsString());
        log(response.toString() + "\n");
        if (responseCode != OK) {
            try {
                throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return response;
    } catch (IOException ioe) {
        throw new WeiboException(ioe.getMessage(), ioe, responseCode);
    } finally {
        method.releaseConnection();
    }
}
Also used : WeiboException(weibo4j.model.WeiboException) Header(org.apache.commons.httpclient.Header) ArrayList(java.util.ArrayList) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 48 with Header

use of org.apache.commons.httpclient.Header in project openhab1-addons by openhab.

the class Telegram method sendTelegram.

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
    postMethod.setRequestBody(data);
    try {
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 49 with Header

use of org.apache.commons.httpclient.Header 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)

Example 50 with Header

use of org.apache.commons.httpclient.Header in project intellij-community by JetBrains.

the class YouTrackIntegrationTest method createIssue.

@NotNull
private String createIssue(@NotNull HttpClient client) throws IOException {
    // http PUT "http://trackers-tests.labs.intellij.net:8067/rest/issue" project==BTYT4TT "summary==First issue created via REST API" 
    final PutMethod method = new PutMethod(myRepository.getUrl() + "/rest/issue");
    method.setQueryString(new NameValuePair[] { new NameValuePair("project", "BTYT4TT"), new NameValuePair("summary", "Test issue for time tracking updates (" + SHORT_TIMESTAMP_FORMAT.format(new Date()) + ")") });
    final int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, statusCode);
    final Header locationHeader = method.getResponseHeader("Location");
    assertNotNull(locationHeader);
    // Otherwise there will be timeout on connection acquiring
    method.releaseConnection();
    return PathUtil.getFileName(locationHeader.getValue());
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) Header(org.apache.commons.httpclient.Header) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Date(java.util.Date) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Header (org.apache.commons.httpclient.Header)93 GetMethod (org.apache.commons.httpclient.methods.GetMethod)23 Test (org.junit.Test)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)21 IOException (java.io.IOException)20 HttpClient (org.apache.commons.httpclient.HttpClient)20 NameValuePair (org.apache.commons.httpclient.NameValuePair)18 HttpMethod (org.apache.commons.httpclient.HttpMethod)17 ArrayList (java.util.ArrayList)16 InputStream (java.io.InputStream)14 HttpException (org.apache.commons.httpclient.HttpException)13 PutMethod (org.apache.commons.httpclient.methods.PutMethod)10 Account (com.zimbra.cs.account.Account)9 ServiceException (com.zimbra.common.service.ServiceException)6 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)6 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)6 Pair (com.zimbra.common.util.Pair)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 HashMap (java.util.HashMap)5 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)5