Search in sources :

Example 6 with URIException

use of org.apache.commons.httpclient.URIException in project zm-mailbox by Zimbra.

the class SoapDebugListener method sendSoapMessage.

@Override
public void sendSoapMessage(PostMethod postMethod, Element envelope, HttpState httpState) {
    if (level == Level.OFF) {
        return;
    }
    System.out.println();
    System.out.println("=== Request ===");
    if (Level.needsHeader(level)) {
        try {
            URI uri = postMethod.getURI();
            System.out.println(uri.toString());
        } catch (URIException e) {
            e.printStackTrace();
        }
        // headers
        Header[] headers = postMethod.getRequestHeaders();
        for (Header header : headers) {
            // trim the ending crlf
            System.out.println(header.toString().trim());
        }
        System.out.println();
        //cookies
        if (httpState != null) {
            Cookie[] cookies = httpState.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println("Cookie: " + cookie.toString());
            }
        }
        System.out.println();
    }
    if (Level.needsBody(level)) {
        System.out.println(envelope.prettyPrint());
    }
}
Also used : Cookie(org.apache.commons.httpclient.Cookie) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) URI(org.apache.commons.httpclient.URI)

Example 7 with URIException

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

the class AbstractRequest method executeUrl.

/**
     * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
     * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
     * 
     * @param httpMethod
     *            the HTTP method to use
     * @param url
     *            the url to execute (in milliseconds)
     * @param contentString
     *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
     *            sent.
     * @param contentType
     *            the content type of the given <code>contentString</code>
     * @return the response body or <code>NULL</code> when the request went wrong
     */
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
    HttpClient client = new HttpClient();
    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(httpRequestTimeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }
    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }
        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }
        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    return null;
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 8 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class HttpMethodHelper method createRequestMethod.

//  This is the currently in use method.
// may be replaced by the New method - however the New method is not yet fully tested so this is stil used.
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;
    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();
    if (method == null || method.trim().length() < 3) {
        throw new URIException("Invalid HTTP method: " + method);
    }
    if (method.equalsIgnoreCase(GET)) {
        //httpMethod = new GetMethod();
        // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade 
        httpMethod = new ZapGetMethod();
    } else if (method.equalsIgnoreCase(POST)) {
        httpMethod = new ZapPostMethod();
    } else if (method.equalsIgnoreCase(DELETE)) {
        httpMethod = new ZapDeleteMethod();
    } else if (method.equalsIgnoreCase(PUT)) {
        httpMethod = new ZapPutMethod();
    } else if (method.equalsIgnoreCase(HEAD)) {
        httpMethod = new ZapHeadMethod();
    } else if (method.equalsIgnoreCase(OPTIONS)) {
        httpMethod = new ZapOptionsMethod();
    } else if (method.equalsIgnoreCase(TRACE)) {
        httpMethod = new ZapTraceMethod(uri.toString());
    } else {
        httpMethod = new GenericMethod(method);
    }
    try {
        httpMethod.setURI(uri);
    } catch (Exception e1) {
        throw new URIException("Failed to set URI [" + uri + "]: " + e1.getMessage());
    }
    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }
    // set various headers
    int pos = 0;
    // ZAP: changed to always use CRLF, like the HttpHeader
    Pattern pattern = patternCRLF;
    String delimiter = header.getLineDelimiter();
    // ZAP: Shouldn't happen as the HttpHeader always uses CRLF
    if (delimiter.equals(LF)) {
        delimiter = LF;
        pattern = patternLF;
    }
    String msg = header.getHeadersAsString();
    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }
        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    // set body if post method or put method
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        //			post.setRequestEntity(new StringRequestEntity(body.toString()));
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
Also used : ZapPutMethod(org.zaproxy.zap.network.ZapPutMethod) Pattern(java.util.regex.Pattern) ZapGetMethod(org.zaproxy.zap.ZapGetMethod) ZapTraceMethod(org.zaproxy.zap.network.ZapTraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) ZapOptionsMethod(org.zaproxy.zap.network.ZapOptionsMethod) ZapHeadMethod(org.zaproxy.zap.network.ZapHeadMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException) URIException(org.apache.commons.httpclient.URIException) ZapPostMethod(org.zaproxy.zap.network.ZapPostMethod) ZapDeleteMethod(org.zaproxy.zap.network.ZapDeleteMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 9 with URIException

use of org.apache.commons.httpclient.URIException in project zaproxy by zaproxy.

the class AbstractDefaultFilePlugin method addTest.

protected void addTest(String directories, String files) {
    String[] dirList = null, fileList = null;
    String dir = "", file = "";
    directories = directories.trim();
    files = files.trim();
    for (int i = 0; i < SPECIAL_TAG_LIST.length; i++) {
        directories = directories.replaceAll(SPECIAL_TAG_LIST[i], TAG_REPLACE_LIST[i]);
    }
    try {
        dirList = patternItems.split(directories);
        fileList = patternItems.split(files);
        for (int i = 0; i < dirList.length; i++) {
            dir = dirList[i].trim();
            if (!dir.startsWith("/")) {
                dir = "/" + dir;
            }
            for (int j = 0; j < fileList.length; j++) {
                file = fileList[j].trim();
                try {
                    URI uri = createURI(baseURI, dir, file);
                    listURI.add(uri);
                } catch (URIException eu) {
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
Also used : URIException(org.apache.commons.httpclient.URIException) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException)

Example 10 with URIException

use of org.apache.commons.httpclient.URIException in project alfresco-remote-api by Alfresco.

the class HttpResponse method toString.

public String toString() {
    StringBuilder sb = new StringBuilder();
    String requestType = null;
    RequestEntity requestEntity = null;
    if (method instanceof GetMethod) {
        requestType = "GET";
    } else if (method instanceof PutMethod) {
        requestType = "PUT";
        requestEntity = ((PutMethod) method).getRequestEntity();
    } else if (method instanceof PostMethod) {
        requestType = "POST";
        requestEntity = ((PostMethod) method).getRequestEntity();
    } else if (method instanceof DeleteMethod) {
        requestType = "DELETE";
    }
    try {
        sb.append(requestType).append(" request ").append(method.getURI()).append("\n");
    } catch (URIException e) {
    }
    if (requestEntity != null) {
        sb.append("\nRequest body: ");
        if (requestEntity instanceof StringRequestEntity) {
            sb.append(((StringRequestEntity) requestEntity).getContent());
        } else if (requestEntity instanceof ByteArrayRequestEntity) {
            sb.append(" << ").append(((ByteArrayRequestEntity) requestEntity).getContent().length).append(" bytes >>");
        }
        sb.append("\n");
    }
    sb.append("user ").append(user).append("\n");
    sb.append("returned ").append(method.getStatusCode()).append(" and took ").append(time).append("ms").append("\n");
    String contentType = null;
    Header hdr = method.getResponseHeader("Content-Type");
    if (hdr != null) {
        contentType = hdr.getValue();
    }
    sb.append("Response content type: ").append(contentType).append("\n");
    if (contentType != null) {
        sb.append("\nResponse body: ");
        if (contentType.startsWith("text/plain") || contentType.startsWith("application/json")) {
            sb.append(getResponse());
            sb.append("\n");
        } else if (getResponseAsBytes() != null) {
            sb.append(" << ").append(getResponseAsBytes().length).append(" bytes >>");
            sb.append("\n");
        }
    }
    return sb.toString();
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Aggregations

URIException (org.apache.commons.httpclient.URIException)52 URI (org.apache.commons.httpclient.URI)31 IOException (java.io.IOException)9 HttpMethod (org.apache.commons.httpclient.HttpMethod)8 Header (org.apache.commons.httpclient.Header)7 HttpClient (org.apache.commons.httpclient.HttpClient)6 ArrayList (java.util.ArrayList)5 Matcher (java.util.regex.Matcher)5 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)5 GetMethod (org.apache.commons.httpclient.methods.GetMethod)5 DatabaseException (org.parosproxy.paros.db.DatabaseException)5 HttpMalformedHeaderException (org.parosproxy.paros.network.HttpMalformedHeaderException)4 BufferedReader (java.io.BufferedReader)3 File (java.io.File)3 InputStreamReader (java.io.InputStreamReader)3 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 HttpException (org.apache.commons.httpclient.HttpException)3 HttpMessage (org.parosproxy.paros.network.HttpMessage)3 InvalidParameterException (java.security.InvalidParameterException)2 HashMap (java.util.HashMap)2