Example usage for java.net HttpURLConnection getHeaderFieldKey

List of usage examples for java.net HttpURLConnection getHeaderFieldKey

Introduction

In this page you can find the example usage for java.net HttpURLConnection getHeaderFieldKey.

Prototype

public String getHeaderFieldKey(int n) 

Source Link

Document

Returns the key for the n th header field.

Usage

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public String SendPost(String httpURL, String data, String _cookie) throws IOException {
    URL url = new URL(httpURL);
    //URL url = new URL("http://zoff.cc/xx.cgi");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);/*from   w  w w.j ava2s . c o m*/
    connection.setRequestProperty("Connection", "Keep-Alive");

    //System.out.println("C=" + _cookie);
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
    connection.setRequestProperty("Cookie", _cookie);
    connection.connect();

    if (data != "") {
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(data);
        out.flush();
        out.close();
    }

    // Save Cookie
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()),
            HTMLDownloader.default_buffer_size);
    String headerName = null;
    //_cookies.clear();
    if (_cookie == "") {
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase("Set-Cookie")) {
                String cookie = connection.getHeaderField(i);
                _cookie += cookie.substring(0, cookie.indexOf(";")) + "; ";
            }
        }
    }

    // Get HTML from Server
    String getData = "";
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        getData += decodedString + "\n";
    }
    in.close();

    return getData;
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ????.//from  w ww  .j  a  v a 2  s  .  c o m
 * 
 * @param url
 *            ?
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (StrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e(FileUtil.class, "???");
    }
    return name;
}

From source file:com.portfolio.data.attachment.XSLService.java

void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer)
        throws MalformedURLException, IOException {
    /// Receive answer
    InputStream in;//from   w w  w.j ava2  s . com
    try {
        in = connection.getInputStream();
    } catch (Exception e) {
        System.out.println(e.toString());
        in = connection.getErrorStream();
    }

    String ref = null;
    if (referer != null) {
        int first = referer.indexOf('/', 7);
        int last = referer.lastIndexOf('/');
        ref = referer.substring(first, last);
    }

    response.setContentType(connection.getContentType());
    response.setStatus(connection.getResponseCode());
    response.setContentLength(connection.getContentLength());

    /// Transfer headers
    Map<String, List<String>> headers = connection.getHeaderFields();
    int size = headers.size();
    for (int i = 1; i < size; ++i) {
        String key = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        //         response.setHeader(key, value);
        response.addHeader(key, value);
    }

    /// Deal with correct path with set cookie
    List<String> setValues = headers.get("Set-Cookie");
    if (setValues != null) {
        String setVal = setValues.get(0);
        int pathPlace = setVal.indexOf("Path=");
        if (pathPlace > 0) {
            setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break
            setVal = setVal + ref;

            response.setHeader("Set-Cookie", setVal);
        }
    }

    /// Write back data
    DataInputStream stream = new DataInputStream(in);
    byte[] buffer = new byte[1024];
    //       int size;
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        while ((size = stream.read(buffer, 0, buffer.length)) != -1)
            out.write(buffer, 0, size);

    } catch (Exception e) {
        System.out.println(e.toString());
        System.out.println("Writing messed up!");
    } finally {
        in.close();
        out.flush(); // close() should flush already, but Tomcat 5.5 doesn't
        out.close();
    }
}

From source file:iracing.webapi.IracingWebApi.java

private boolean forumLoginAndGetCookie() {
    try {/*from  w  w w . ja  va2 s  .c o  m*/
        // Make a connect to the server
        URL url = new URL(FORUM_LOGIN_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.addRequestProperty(COOKIE, cookie);

        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);
        HttpURLConnection.setFollowRedirects(false);

        conn.connect();

        if (isMaintenancePage(conn))
            return false;

        String headerName;
        boolean containsCookie = false;
        for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equalsIgnoreCase(SET_COOKIE)) {
                containsCookie = true;
                addToCookieMap(conn.getHeaderField(i));
            }
        }
        if (containsCookie)
            createCookieFromMap();

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
    return true;
}

From source file:fr.zcraft.zbanque.network.PacketSender.java

private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data)
        throws Throwable {
    // ***  REQUEST  ***

    final URL urlObj = new URL(url);
    final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

    connection.setRequestMethod(method.name());
    connection.setRequestProperty("User-Agent", USER_AGENT);

    authenticateRequest(connection);/* ww  w.  j ava 2  s  . co m*/

    connection.setDoOutput(true);

    try {
        try {
            connection.connect();
        } catch (IOException ignored) {
        }

        if (method == PacketPlayOut.PacketType.POST) {
            DataOutputStream out = null;
            try {
                out = new DataOutputStream(connection.getOutputStream());
                if (data != null)
                    out.writeBytes(data);
                out.flush();
            } finally {
                if (out != null)
                    out.close();
            }
        }

        // ***  RESPONSE  ***

        int responseCode;
        boolean failed = false;

        try {
            responseCode = connection.getResponseCode();
        } catch (IOException e) {
            // HttpUrlConnection will throw an IOException if any 4XX
            // response is sent. If we request the status again, this
            // time the internal status will be properly set, and we'll be
            // able to retrieve it.
            // Thanks to Iigo.
            responseCode = connection.getResponseCode();
            failed = true;
        }

        BufferedReader in = null;
        String body = "";
        try {
            InputStream stream;
            try {
                stream = connection.getInputStream();
            } catch (IOException e) {
                // Same as before
                stream = connection.getErrorStream();
                failed = true;
            }

            in = new BufferedReader(new InputStreamReader(stream));
            StringBuilder responseBuilder = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseBuilder.append(inputLine);
            }

            body = responseBuilder.toString();
        } finally {
            if (in != null)
                in.close();
        }

        HTTPResponse response = new HTTPResponse();
        response.setResponseCode(responseCode, failed);
        response.setResponseBody(body);

        int i = 0;
        String headerName, headerContent;
        while ((headerName = connection.getHeaderFieldKey(i)) != null) {
            headerContent = connection.getHeaderField(i);
            response.addHeader(headerName, headerContent);
        }

        // ***  REDIRECTION  ***

        switch (responseCode) {
        case 301:
        case 302:
        case 307:
        case 308:
            if (response.getHeaders().containsKey("Location")) {
                response = makeRequest(response.getHeaders().get("Location"), method, data);
            }
        }

        // ***  END  ***

        return response;
    } finally {
        connection.disconnect();
    }
}

From source file:org.sogrey.frame.utils.FileUtil.java

/**
 * ????./*from w w w  . j a  v  a  2  s .c  o  m*/
 *
 * @param url
 *         ?
 *
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (StrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e(FileUtil.class, "???");
    }
    return name;
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getDHttpPage(PageRef url, String charSet) {
    count++;//from w w w.  ja v a 2s.c o  m
    log.debug("getURL(" + count + ")");

    if (url.getUrlStr() == null) {
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    URL requestedURL = null;
    try {
        requestedURL = new URL(url.getUrlStr());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        log.error("wrong urlstr" + url.getUrlStr());
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new OriHttpPage(-1, null, null, null, conRes, null);
    }
    ;
    //        System.out.println(""+requestedURL.toExternalForm());
    URL referer = null;
    try {
        log.debug("Creating HTTP connection to " + requestedURL);
        HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection();
        if (referer != null) {
            log.debug("Setting Referer header to " + referer);
            conn.setRequestProperty("Referer", referer.toExternalForm());
        }

        if (userAgent != null) {
            log.debug("Setting User-Agent to " + userAgent);
            conn.setRequestProperty("User-Agent", userAgent);
        }

        //            DateFormat dateFormat=DateFormat.getDateInstance();
        //            conn.setRequestProperty("If-Modlfied-Since",dateFormat.parse("2005-08-15 20:18:30").toGMTString());
        conn.setUseCaches(false);

        //            conn.setRequestProperty("connection","keep-alive");
        for (Iterator it = conn.getRequestProperties().keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Request header " + key + ": " + value);
        }
        log.debug("Opening URL");
        long startTime = System.currentTimeMillis();
        conn.connect();

        String resp = conn.getResponseMessage();
        log.debug("Remote server response: " + resp);

        int code = conn.getResponseCode();

        if (code != 200) {
            log.error("Could not get connection for code=" + code);
            System.err.println("Could not get connection for code=" + code);
            ConnResponse conRes = new ConnResponse(null, null, 0, 0, code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
        }

        //            if (conn.getContentLength()<=0||conn.getContentLength()>10000000){
        //               log.error("Content length==0");
        //               System.err.println("Content length==0");
        //               ConnResponse conRes=new ConnResponse(null,null,null,0,0,-100);
        //               return new URLObject(-1,requestedURL, null,null,conRes);
        //            }

        String respStr = conn.getHeaderField(0);
        long serverDate = conn.getDate();
        //            log.info("Server response: " + respStr);

        for (int i = 1; i < conn.getHeaderFields().size(); i++) {
            String key = conn.getHeaderFieldKey(i);
            if (key == null) {
                break;
            }
            String value = conn.getHeaderField(key);
            //                System.out.println("Received header " + key + ": " + value);
            //               log.debug("Received header " + key + ": " + value);
        }

        //            log.debug("Getting buffered input stream from remote connection");
        log.debug("start download(" + count + ")");
        BufferedInputStream remoteBIS = new BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream(10240);
        byte[] buf = new byte[1024];
        int bytesRead = 0;
        while (bytesRead >= 0) {
            baos.write(buf, 0, bytesRead);
            bytesRead = remoteBIS.read(buf);
        }
        //            baos.write(remoteBIS.read(new byte[conn.getContentLength()]));
        //            remoteBIS.close();
        byte[] content = baos.toByteArray();
        long timeTaken = System.currentTimeMillis() - startTime;
        if (timeTaken < 100)
            timeTaken = 500;

        int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0));
        //            log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec");
        if (content.length < conn.getContentLength()) {
            log.warn("Didn't download full content for URL: " + url);
            //                failureCount++;
            ConnResponse conRes = new ConnResponse(conn.getContentType(), null, content.length, serverDate,
                    code);
            return new HttpPage(requestedURL.toExternalForm(), null, conRes, conn.getContentType());
        }

        log.debug("download(" + count + ")");

        ConnResponse conRes = new ConnResponse(conn.getContentType(), null, conn.getContentLength(), serverDate,
                code);
        String c = charSet;
        if (c == null)
            c = conRes.getCharSet();
        HttpPage obj = new HttpPage(requestedURL.toExternalForm(), content, conRes, c);
        return obj;
    } catch (IOException ioe) {
        log.warn("Caught IO Exception: " + ioe.getMessage(), ioe);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    } catch (Exception e) {
        log.warn("Caught Exception: " + e.getMessage(), e);
        failureCount++;
        ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0);
        return new HttpPage(requestedURL.toExternalForm(), null, conRes, null);
    }
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);/*from   ww  w .j ava 2  s  .c  o  m*/
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

        connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length));

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}

From source file:com.sun.faces.systest.ant.SystestClient.java

/**
 * Execute the test via use of an HttpURLConnection.
 *
 * @throws BuildException if an exception occurs
 *///from w  w  w  .  j  a  v  a2s .  co m
protected void executeHttp() throws BuildException {

    // Construct a summary of the request we will be sending
    String summary = "[" + method + " " + request + "]";
    boolean success = true;
    String result = null;
    Throwable throwable = null;
    HttpURLConnection conn = null;

    try {

        // Configure an HttpURLConnection for this request
        if (log.isDebugEnabled()) {
            log.debug("Configuring HttpURLConnection for this request");
        }
        URL url = new URL("http", host, port, request);
        conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        conn.setDoInput(true);
        if (inContent != null) {
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + inContent.length());
            if (log.isTraceEnabled()) {
                log.trace("INPH: Content-Length: " + inContent.length());
            }
        } else {
            conn.setDoOutput(false);
        }

        // Send the session id cookie (if any)
        if (joinSession && (sessionId != null)) {
            conn.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
            if (log.isTraceEnabled()) {
                log.trace("INPH: Cookie: JSESSIONID=" + sessionId);
            }
        }

        if (this.redirect && log.isTraceEnabled()) {
            log.trace("FLAG: setInstanceFollowRedirects(" + this.redirect + ")");
        }
        conn.setInstanceFollowRedirects(this.redirect);
        conn.setRequestMethod(method);
        if (inHeaders != null) {
            String headers = inHeaders;
            while (headers.length() > 0) {
                int delimiter = headers.indexOf("##");
                String header = null;
                if (delimiter < 0) {
                    header = headers;
                    headers = "";
                } else {
                    header = headers.substring(0, delimiter);
                    headers = headers.substring(delimiter + 2);
                }
                int colon = header.indexOf(":");
                if (colon < 0)
                    break;
                String name = header.substring(0, colon).trim();
                String value = header.substring(colon + 1).trim();
                conn.setRequestProperty(name, value);
                if (log.isTraceEnabled()) {
                    log.trace("INPH: " + name + ": " + value);
                }
            }
        }

        // Connect to the server and send our output if necessary
        conn.connect();
        if (inContent != null) {
            if (log.isTraceEnabled()) {
                log.trace("INPD: " + inContent);
            }
            OutputStream os = conn.getOutputStream();
            for (int i = 0, length = inContent.length(); i < length; i++)
                os.write(inContent.charAt(i));
            os.close();
        }

        // Acquire the response data, if there is any
        String outData = "";
        String outText = "";
        boolean eol = false;
        InputStream is = conn.getInputStream();
        int lines = 0;
        while (true) {
            String line = read(is);
            if (line == null)
                break;
            if (lines == 0)
                outData = line;
            else
                outText += line + "\r\n";
            saveResponse.add(line);
            lines++;
        }
        is.close();

        // Dump out the response stuff
        if (log.isTraceEnabled()) {
            log.trace("RESP: " + conn.getResponseCode() + " " + conn.getResponseMessage());
        }
        for (int i = 1; i < 1000; i++) {
            String name = conn.getHeaderFieldKey(i);
            String value = conn.getHeaderField(i);
            if ((name == null) || (value == null))
                break;
            if (log.isTraceEnabled()) {
                log.trace("HEAD: " + name + ": " + value);
            }
            save(name, value);
            if ("Set-Cookie".equals(name))
                parseSession(value);
        }
        if (log.isTraceEnabled()) {
            log.trace("DATA: " + outData);
            if (outText.length() > 2) {
                log.trace("TEXT: " + outText);
            }
        }

        // Validate the response against our criteria
        if (success) {
            result = validateStatus(conn.getResponseCode());
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateMessage(conn.getResponseMessage());
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateHeaders();
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateData(outData);
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateGolden();
            if (result != null)
                success = false;
        }

    } catch (Throwable t) {
        if (t instanceof FileNotFoundException) {
            if (status == 404) {
                success = true;
                result = "Not Found";
                throwable = null;
            } else {
                success = false;
                try {
                    result = "Status=" + conn.getResponseCode() + ", Message=" + conn.getResponseMessage();
                } catch (IOException e) {
                    result = e.toString();
                }
                throwable = null;
            }
        } else if (t instanceof ConnectException) {
            success = false;
            result = t.getMessage();
            throwable = null;
        } else {
            success = false;
            result = t.getMessage();
            throwable = t;
        }
    }

    // Log the results of executing this request
    if (success) {
        System.out.println("OK   " + summary);
    } else {
        System.out.println("FAIL " + summary + " " + result);
        if (throwable != null)
            throwable.printStackTrace(System.out);
        if (failonerror) {
            if (throwable != null) {
                throw new BuildException("System test failed", throwable);
            } else {
                throw new BuildException("System test failed");
            }
        }
    }

}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Tunnels a request to the online application using given URL mapping and SSLSocketFactory.
 * This method returns the ResponseCode of the request to the online application. 
 * @param req HTTP request//from   www  .j  a v a 2s.co m
 * @param resp HTTP response
 * @param loginHeaders header field/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param loginParameters parameter name/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param publicURLPrefix prefix of request URL to be substituted for the <code>realURLPrefix</code>
 * @param realURLPrefix prefix of online application URL to substitute the <code>publicURLPrefix</code>
 * @param ssf SSLSocketFactory to use
 * @throws IOException if an I/O error occurs
 */
private int tunnelRequest(HttpServletRequest req, HttpServletResponse resp, Map loginHeaders,
        Map loginParameters, String publicURLPrefix, String realURLPrefix, SSLSocketFactory ssf, String binding)
        throws IOException {

    String originBinding = binding;
    String browserUserID = "";
    String browserPassword = "";
    //URL url = new URL(realURLPrefix); 
    //String realURLHost = url.getHost(); 
    if (INTERNAL_DEBUG && !binding.equals(""))
        Logger.debug("Binding: " + binding);

    // collect headers from request
    Map headers = new HashMap();
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String headerKey = (String) enu.nextElement();
        String headerKeyValue = req.getHeader(headerKey);
        if (INTERNAL_DEBUG)
            Logger.debug("Incoming:" + headerKey + "=" + headerKeyValue);
        //Analyze Basic-Auth-Headers from the client
        if (headerKey.equalsIgnoreCase("Authorization")) {
            if (headerKeyValue.substring(0, 6).equalsIgnoreCase("Basic ")) {
                String credentials = headerKeyValue.substring(6);
                byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                String plaintextcredentials = new String(bplaintextcredentials);
                browserUserID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                browserPassword = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
            if (headerKeyValue.substring(0, 9).equalsIgnoreCase("Negotiate")) {
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: Found NTLM Aut.: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
        } else {
            /* Headers MUST NOT be repaced according to our Spec.
            if (headerKey.equalsIgnoreCase("Host")) {
               headerKeyValue = realURLHost; 
                 //headerKeyValue= realURLPrefix.substring(hoststartpos);
              if (INTERNAL_DEBUG) Logger.debug("replaced:" + headerKey + "=" + headerKeyValue);           
            }
            */
            headers.put(headerKey, headerKeyValue);
        }
    }

    // collect login headers, possibly overwriting headers from request
    String authorizationvalue = "";
    if (req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {

        if (OAConfiguration.BINDUNG_NOMATCH.equals(binding)) {
            int loginTry = getLoginTry(req);
            Logger.debug("Binding: mode = " + OAConfiguration.BINDUNG_NOMATCH + "(try #"
                    + Integer.toString(loginTry) + ")");
            if (loginTry == 1) {
                binding = OAConfiguration.BINDUNG_FULL;
            } else {
                binding = OAConfiguration.BINDUNG_USERNAME;
            }
        }

        /* Soll auch bei anderen bindings zuerst ein passwort probiert werden knnen:
        //if we have the first Login-Try and we have Binding to Username and a predefined Password we try this one first
         // full binding will be covered by next block
         if (loginTry==1 && !OAConfiguration.BINDUNG_FULL.equals(binding)) {
           //1st try: if we have a password, try this one first
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
              String headerKey = (String) iter.next();
              String headerKeyValue = (String) loginHeaders.get(headerKey);
              if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
               String credentials = headerKeyValue.substring(6);
               byte [] bplaintextcredentials = Base64Utils.decode(credentials, true);
              String plaintextcredentials = new String(bplaintextcredentials);
              String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":")+1);
              if (password!=null && !password.equals("")) {
                  Logger.debug("Binding: found predefined password. Trying full binding first");
                 binding = OAConfiguration.BINDUNG_FULL;
                 break;
                }
              }
            }
         }
         */

        //we have a connection with not having logged on
        if (loginHeaders != null && (browserPassword.length() != 0 || browserUserID.length() != 0
                || OAConfiguration.BINDUNG_FULL.equals(binding))) {
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                String headerKey = (String) iter.next();
                String headerKeyValue = (String) loginHeaders.get(headerKey);
                //customize loginheaders if necessary
                if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
                    if (OAConfiguration.BINDUNG_FULL.equals(binding)) {
                        authorizationvalue = headerKeyValue;
                        Logger.debug("Binding: full binding to user established");
                    } else {
                        String credentials = headerKeyValue.substring(6);
                        byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                        String plaintextcredentials = new String(bplaintextcredentials);
                        String userID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                        String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                        String userIDPassword = ":";
                        if (OAConfiguration.BINDUNG_USERNAME.equals(binding)) {
                            Logger.debug("Binding: Access with necessary binding to user");
                            userIDPassword = userID + ":" + browserPassword;
                        } else if (OAConfiguration.BINDUNG_NONE.equals(binding)) {
                            Logger.debug("Binding: Access without binding to user");
                            //If first time
                            if (browserUserID.length() == 0)
                                browserUserID = userID;
                            if (browserPassword.length() == 0)
                                browserPassword = password;
                            userIDPassword = browserUserID + ":" + browserPassword;
                        } else {
                            userIDPassword = userID + ":" + password;
                        }
                        credentials = Base64Utils.encode(userIDPassword.getBytes());
                        authorizationvalue = "Basic " + credentials;
                        headerKeyValue = authorizationvalue;
                    }
                }
                headers.put(headerKey, headerKeyValue);
            }
        }
    } else {
        //if OA needs Authorization header in each further request
        authorizationvalue = (String) req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER);
        if (loginHeaders != null)
            headers.put("Authorization", authorizationvalue);
    }

    Vector parameters = new Vector();
    for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) {
        String paramName = (String) enu.nextElement();
        if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
            if (INTERNAL_DEBUG)
                Logger.debug("Req Parameter-put: " + paramName + ":" + req.getParameter(paramName));
            String parameter[] = new String[2];
            parameter[0] = paramName;
            parameter[1] = req.getParameter(paramName);
            parameters.add(parameter);
        }
    }
    // collect login parameters, possibly overwriting parameters from request
    if (loginParameters != null) {
        for (Iterator iter = loginParameters.keySet().iterator(); iter.hasNext();) {
            String paramName = (String) iter.next();
            if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
                if (INTERNAL_DEBUG)
                    Logger.debug(
                            "Req Login-Parameter-put: " + paramName + ":" + loginParameters.get(paramName));
                String parameter[] = new String[2];
                parameter[0] = paramName;
                parameter[1] = (String) loginParameters.get(paramName);
                parameters.add(parameter);
            }
        }
    }

    ConnectionBuilder cb = ConnectionBuilderFactory.getConnectionBuilder(publicURLPrefix);
    HttpURLConnection conn = cb.buildConnection(req, publicURLPrefix, realURLPrefix, ssf, parameters);

    // set headers as request properties of URLConnection
    for (Iterator iter = headers.keySet().iterator(); iter.hasNext();) {
        String headerKey = (String) iter.next();
        String headerValue = (String) headers.get(headerKey);
        String LogStr = "Req header " + headerKey + ": " + headers.get(headerKey);
        if (isBasicAuthenticationHeader(headerKey, headerValue)) {
            String credentials = headerValue.substring(6);
            byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
            String plaintextcredentials = new String(bplaintextcredentials);
            String uid = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
            String pwd = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
            //Sollte AuthorizationInfo vom HTTPClient benutzt werden:  cb.addBasicAuthorization(publicURLPrefix, uid, pwd);
            //deactivate following line for security
            //if (INTERNAL_DEBUG && Logger.isDebugEnabled()) LogStr = LogStr + "  >UserID:Password< >" + uid + ":" + pwd + "<";
        }
        conn.setRequestProperty(headerKey, headerValue);
        if (INTERNAL_DEBUG)
            Logger.debug(LogStr);
    }

    StringWriter sb = new StringWriter();

    // Write out parameters into output stream of URLConnection.
    // On GET request, do not send parameters in any case,
    // otherwise HttpURLConnection would send a POST.
    if (!"get".equalsIgnoreCase(req.getMethod()) && !parameters.isEmpty()) {
        boolean firstParam = true;
        String parameter[] = new String[2];
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            parameter = (String[]) iter.next();
            String paramName = parameter[0];
            String paramValue = parameter[1];
            if (firstParam)
                firstParam = false;
            else
                sb.write("&");
            sb.write(paramName);
            sb.write("=");
            sb.write(paramValue);
            if (INTERNAL_DEBUG)
                Logger.debug("Req param " + paramName + ": " + paramValue);
        }
    }

    // For WebDAV and POST: copy content
    if (!"get".equalsIgnoreCase(req.getMethod())) {
        if (INTERNAL_DEBUG && !"post".equalsIgnoreCase(req.getMethod()))
            Logger.debug("---- WEBDAV ----  copying content");
        try {
            OutputStream out = conn.getOutputStream();
            InputStream in = req.getInputStream();
            if (!parameters.isEmpty())
                out.write(sb.toString().getBytes()); //Parameter nicht mehr mittels Printwriter schreiben 
            copyStream(in, out, null, req.getMethod());
            out.flush();
            out.close();
        } catch (IOException e) {
            if (!"post".equalsIgnoreCase(req.getMethod()))
                Logger.debug("---- WEBDAV ----  streamcopy problem");
            else
                Logger.debug("---- POST ----  streamcopy problem");
        }
    }

    // connect
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Request");
    conn.connect();
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Response");

    // check login tries
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        int loginTry = getLoginTry(req);
        req.getSession().setAttribute(ATT_OA_LOGINTRY, Integer.toString(loginTry));
        if (loginTry > MAX_OA_LOGINTRY) {
            Logger.debug("Found 401 UNAUTHORIZED, maximum tries exceeded; leaving...");
            cb.disconnect(conn);
            return -401;
        }
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED
            && OAConfiguration.BINDUNG_FULL.equals(originBinding)) {
        Logger.debug("Found 401 UNAUTHORIZED, leaving...");
        cb.disconnect(conn);
        return conn.getResponseCode();
    }

    resp.setStatus(conn.getResponseCode());
    //Issue by Gregor Karlinger - content type was annotated twice
    //resp.setContentType(conn.getContentType());

    if (loginHeaders != null
            && (conn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            && req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {
        req.getSession().setAttribute(ATT_OA_AUTHORIZATION_HEADER, authorizationvalue);
        Logger.debug("Login OK. Saving authorization header to remember in further requests");
    }

    // Read response headers
    // Omit response header "content-length" if response header "Transfer-encoding: chunked" is set.
    // Otherwise, the connection will not be kept alive, resulting in subsequent missing requests.
    // See JavaDoc of javax.servlet.http.HttpServlet:
    // When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
    Vector respHeaders = new Vector();

    boolean chunked = false;
    String contentLengthKey = null;
    String transferEncodingKey = null;
    int i = 1;
    String headerKey;
    String loginType = (String) req.getSession().getAttribute(ATT_OA_LOGINTYPE);
    while ((headerKey = conn.getHeaderFieldKey(i)) != null) {
        String headerValue = conn.getHeaderField(i);

        if (headerKey.equalsIgnoreCase("WWW-Authenticate")) {
            int start = headerValue.indexOf("Basic realm=\"");
            boolean requestsBasicAuth = headerValue.substring(start).startsWith("Basic realm=\"");
            if (requestsBasicAuth) {
                headerValue = "Basic realm=\"" + publicURLPrefix + "\"";

                if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding)
                        || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding))
                    headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
                else if ("none".equals(originBinding)) {
                    headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
                }
            }
        }

        //    // berschrift im Browser-Passworteingabedialog setzen (sonst ist der reale host eingetragen)
        //    if (headerKey.equalsIgnoreCase("WWW-Authenticate") && headerValue.startsWith("Basic realm=\"")) {
        //      headerValue = "Basic realm=\"" + publicURLPrefix + "\"";
        //      if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding) || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
        //      } else if (OAConfiguration.BINDUNG_NONE.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
        //      }
        //    }

        String respHeader[] = new String[2];
        if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
                && headerKey.equalsIgnoreCase("content-length")) {
            //alter the unauthorized message with template for login 
            //TODO: supply a special login form on unauthorized messages with bindings!=full
            headerValue = Integer.toString(RET_401_MSG.length());
        }
        respHeader[0] = headerKey;
        respHeader[1] = headerValue;

        if (!(OAConfiguration.BINDUNG_FULL.equals(originBinding)
                && OAConfiguration.LOGINTYPE_STATELESS.equals(loginType)
                && headerKey.equalsIgnoreCase("WWW-Authenticate")
                && headerValue.startsWith("Basic realm=\""))) {
            respHeaders.add(respHeader);
            if (INTERNAL_DEBUG)
                Logger.debug("Resp header " + headerKey + ": " + headerValue);
        } else {
            Logger.debug("Resp header ---REMOVED--- " + headerKey + ": " + headerValue);
        }
        if (isTransferEncodingChunkedHeader(headerKey, headerValue)
                || "content-length".equalsIgnoreCase(headerKey)) {
            respHeaders.remove(respHeader);
            Logger.debug("Resp header " + headerKey + " REMOVED");
        }

        i++;
    }

    String headerValue;
    String respHeader[] = new String[2];

    //write out all Responseheaders 
    for (Iterator iter = respHeaders.iterator(); iter.hasNext();) {
        respHeader = (String[]) iter.next();
        headerKey = respHeader[0];
        headerValue = respHeader[1];
        resp.addHeader(headerKey, headerValue);
    }

    //Logger.debug(">>>> Copy Content");
    //Logger.debug("  from ()" + conn.getURL());
    //Logger.debug("  to (" + req.getRemoteAddr() + ":"+ ") " +req.getRequestURL());

    // read response stream
    Logger.debug("Resp from " + conn.getURL().toString() + ": status " + conn.getResponseCode());
    // Load content unless the server lets us know that the content is NOT MODIFIED...
    if (conn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        BufferedInputStream respIn = new BufferedInputStream(conn.getInputStream());
        //Logger.debug("Got Inputstream");
        BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
        //Logger.debug("Got Outputstream");

        byte[] buffer = new byte[4096];
        if (respOut != null) {
            int bytesRead;
            while ((bytesRead = respIn.read(buffer)) >= 0) {
                if (conn.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED)
                    respOut.write(buffer, 0, bytesRead);
            }
        } else {
            while (respIn.read(buffer) >= 0)
                ;
        }

        /*
        int ch;
        StringBuffer strBuf = new StringBuffer("");
        while ((ch = respIn.read()) >= 0) {
          if (conn.getResponseCode()!=HttpURLConnection.HTTP_UNAUTHORIZED) respOut.write(ch);
          strBuf.append((char)ch);
        }
        Logger.debug("Resp Content:");
        if (strBuf.toString().length()>500)
          Logger.debug(strBuf.toString().substring(0,500));
        else
          Logger.debug(strBuf.toString());
        */

        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            respOut.write(RET_401_MSG.getBytes());
        }
        respOut.flush();
        respOut.close();
        respIn.close();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Logger.debug("Found 401 UNAUTHORIZED...");
            cb.disconnect(conn);
            return conn.getResponseCode();
        }
    } else {
        //if (conn.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED) 
        Logger.debug("Found 304 NOT MODIFIED...");
    }

    cb.disconnect(conn);
    Logger.debug("Request done");

    return conn.getResponseCode();
}