Example usage for org.apache.commons.httpclient HttpMethod getURI

List of usage examples for org.apache.commons.httpclient HttpMethod getURI

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getURI.

Prototype

public abstract URI getURI() throws URIException;

Source Link

Usage

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0:/*ww  w  .  j  a  v  a  2s.c o m*/
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

From source file:org.infoscoop.request.NTLMAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    try {// ww w. j a va  2 s  .c  om
        client.getParams().setAuthenticationPreemptive(true);
        String[] uidDomain = uid.split("\\\\");
        String domain = "";
        if (uidDomain.length > 1) {
            domain = uidDomain[0].trim();
            uid = uidDomain[1].trim();
        } else {
            uid = uidDomain[0].trim();
        }
        // create the information of certification(an userID and a password).
        Credentials credentials = new NTCredentials(uid, pwd, domainController, domain);
        // the scope of the certification.
        URL urlObj = new URL(method.getURI().toString());
        AuthScope scope1 = new AuthScope(urlObj.getHost(), urlObj.getPort(), null);
        // set a pair of a scope and an information of the certification.
        client.getState().setCredentials(scope1, credentials);
    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.infoscoop.request.OAuthAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuthConfig oauthConfig = request.getOauthConfig();
    try {//from w w w . j  a va2  s.co  m
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig);
        OAuthAccessor accessor = newAccessor(consumer, oauthConfig);
        if (accessor.accessToken == null) {
            getRequestToken(request, accessor);
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }
        OAuthMessage message = accessor.newRequestMessage(method.getName(), method.getURI().toString(),
                parameters != null ? parameters.entrySet() : null);
        String authHeader = message.getAuthorizationHeader(null);
        request.setRequestHeader("Authorization", authHeader);
        // Find the non-OAuth parameters:
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }

}

From source file:org.mule.transport.as2.As2MuleMessageFactory.java

@Override
protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception {
    String method;//  ww w  .j  ava2s  . co m
    HttpVersion httpVersion;
    String uri;
    String statusCode = null;
    Map<String, Object> headers;
    Map<String, Object> httpHeaders = new HashMap<String, Object>();
    Map<String, Object> queryParameters = new HashMap<String, Object>();

    if (transportMessage instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) transportMessage;
        method = httpRequest.getRequestLine().getMethod();
        httpVersion = httpRequest.getRequestLine().getHttpVersion();
        uri = httpRequest.getRequestLine().getUri();
        headers = convertHeadersToMap(httpRequest.getHeaders(), uri);
        convertMultiPartHeaders(headers);
    } else if (transportMessage instanceof HttpMethod) {
        HttpMethod httpMethod = (HttpMethod) transportMessage;
        method = httpMethod.getName();
        httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion());
        uri = httpMethod.getURI().toString();
        statusCode = String.valueOf(httpMethod.getStatusCode());
        headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri);
    } else {
        // This should never happen because of the supported type checking in our superclass
        throw new MessageTypeNotSupportedException(transportMessage, getClass());
    }

    rewriteConnectionAndKeepAliveHeaders(headers);

    headers = processIncomingHeaders(headers);

    httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers));

    String encoding = getEncoding(headers);

    queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding));

    //Make any URI params available ans inbound message headers
    addUriParamsAsHeaders(headers, uri);

    headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method);
    headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri);
    headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString());
    if (enableCookies) {
        headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec);
    }

    if (statusCode != null) {
        headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode);
    }

    message.addInboundProperties(headers);
    message.addInboundProperties(httpHeaders);
    message.addInboundProperties(queryParameters);

    // The encoding is stored as message property. To avoid overriding it from the message
    // properties, it must be initialized last
    initEncoding(message, encoding);
}

From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java

private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers)
        throws Exception {
    HttpMethod httpMethod = mock(HttpMethod.class);
    when(httpMethod.getName()).thenReturn(method);
    when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK"));
    when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK);
    when(httpMethod.getURI()).thenReturn(new URI(uri, false));
    when(httpMethod.getResponseHeaders()).thenReturn(headers);
    when(httpMethod.getResponseBodyAsStream()).thenReturn(body);

    return httpMethod;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Send a command to the Particle REST API (convenience function).
 *
 * @param device/*from  w ww . ja  va  2 s .  c o  m*/
 *            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();

    // Only perform basic authentication when we aren't using OAuth

    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();
    }
}

From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java

/**
 * 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.
 * // ww w . java 2 s . c o m
 * @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(HTTP_REQUEST_TIMEOUT);
    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;
}

From source file:org.openhab.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * //  w  w  w . ja v a 2 s  . c o m
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(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;
        }

        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.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);
        }

        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;
}

From source file:org.openqa.selenium.remote.HttpCommandExecutor.java

private Response createResponse(HttpMethod httpMethod) throws Exception {
    Response response;// w  w  w  .j  ava 2  s.  co m

    Header header = httpMethod.getResponseHeader("Content-Type");

    if (header != null && header.getValue().startsWith("application/json")) {
        response = new JsonToBeanConverter().convert(Response.class, httpMethod.getResponseBodyAsString());
    } else {
        response = new Response();

        if (header != null && header.getValue().startsWith("image/png")) {
            response.setValue(httpMethod.getResponseBody());
        } else {
            response.setValue(httpMethod.getResponseBodyAsString());
        }

        String uri = httpMethod.getURI().toString();
        int sessionIndex = uri.indexOf("/session/");
        if (sessionIndex != -1) {
            sessionIndex += "/session/".length();
            int nextSlash = uri.indexOf("/", sessionIndex);
            if (nextSlash != -1) {
                response.setSessionId(uri.substring(sessionIndex, nextSlash));
                response.setContext("foo");
            }
        }
    }
    response.setError(!(httpMethod.getStatusCode() > 199 && httpMethod.getStatusCode() < 300));

    if (response.getValue() instanceof String) {
        //We normalise to \n because Java will translate this to \r\n
        //if this is suitable on our platform, and if we have \r\n, java will
        //turn this into \r\r\n, which would be Bad!
        response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
    }

    return response;
}

From source file:org.openrdf.http.client.HTTPClient.java

protected void getRDF(HttpMethod method, RDFHandler handler, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }/*from w  ww  . j a  v a  2s  . c  om*/

    List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, preferredRDFFormat);
    for (String acceptParam : acceptParams) {
        method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats);
            RDFParser parser = Rio.createParser(format, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());
            parser.setRDFHandler(handler);
            parser.parse(method.getResponseBodyAsStream(), method.getURI().getURI());
        } catch (UnsupportedRDFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (RDFParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(errInfo.toString());
        }
    }
}