Example usage for java.net HttpURLConnection HTTP_MOVED_TEMP

List of usage examples for java.net HttpURLConnection HTTP_MOVED_TEMP

Introduction

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

Prototype

int HTTP_MOVED_TEMP

To view the source code for java.net HttpURLConnection HTTP_MOVED_TEMP.

Click Source Link

Document

HTTP Status-Code 302: Temporary Redirect.

Usage

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private byte[] callServerEventImpl(IRtXMASessionClient session, URL url, byte[] input, boolean handleRedirect)
        throws CommunicationException {
    OutputStream serverIn;/* w w w  .  ja v a2  s .c o  m*/
    int code = 0;
    HttpURLConnection conn;
    byte[] buffer = null;

    try {
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        conn.setDoOutput(true);
        conn.setRequestMethod("POST"); //$NON-NLS-1$
        sendCookies(session, url, conn);
        conn.setRequestProperty(Statics.HTTP_CONTENT_TYPE, "application/octet-stream"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "application/octet-stream"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);
        serverIn = conn.getOutputStream();
    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", exc); //$NON-NLS-1$
        throw new ConnectException("error calling '" + url.toString() + "' at the server:", exc);
    }

    try {
        serverIn.write(input);
        serverIn.close();
        code = conn.getResponseCode();

        // if requested, we allow redirect also on POST requests, therewith violating RFC 2616 section 10.3!
        if (handleRedirect && code == HttpURLConnection.HTTP_MOVED_TEMP
                || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        }

        buffer = this.readOutput(conn);
        readCookies(session, url, conn);
        return buffer;
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error calling '" + url.toString() + "' at the server:", ex);
        else
            throw new ServerException("error calling '" + url.toString() + "' at the server:", ex);
    }
}

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Process a page.//from  w  w  w .j  av  a 2s  .  c  o  m
 */
public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        targetURL = new URI(target);
    } catch (URISyntaxException e) {
        IOException ioe = new IOException("Bad URI syntax: " + target);
        ioe.initCause(e);
        throw ioe;
    }
    setHostPrefix(targetURL);

    HttpClient httpClient = new HttpClient();
    HttpState httpState = new HttpState();
    HostConfiguration hostConfig = new HostConfiguration();
    HttpMethodBase httpMethod;

    // define host
    hostConfig.setHost(targetURL.getHost(), targetURL.getPort());

    // create http method
    String method = (String) request.getAttribute("cq.ext.app.method");
    if (method == null) {
        method = request.getMethod();
    }
    method = method.toUpperCase();
    boolean isPost = "POST".equals(method);
    String urlString = targetURL.getPath();
    StringBuffer query = new StringBuffer();
    if (targetURL.getQuery() != null) {
        query.append("?");
        query.append(targetURL.getQuery());
    }
    //------------ GET ---------------
    if ("GET".equals(method)) {
        // add internal props
        Iterator<String> iter = extraParams.keySet().iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String value = extraParams.get(name);
            if (query.length() == 0) {
                query.append("?");
            } else {
                query.append("&");
            }
            query.append(Text.escape(name));
            query.append("=");
            query.append(Text.escape(value));
        }
        if (passInput) {
            // add request params
            @SuppressWarnings("unchecked")
            Enumeration<String> e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                if (targetParamName.equals(name)) {
                    continue;
                }
                String[] values = request.getParameterValues(name);
                for (int i = 0; i < values.length; i++) {
                    if (query.length() == 0) {
                        query.append("?");
                    } else {
                        query.append("&");
                    }
                    query.append(Text.escape(name));
                    query.append("=");
                    query.append(Text.escape(values[i]));
                }
            }

        }
        httpMethod = new GetMethod(urlString + query);
        //------------ POST ---------------
    } else if ("POST".equals(method)) {
        PostMethod m = new PostMethod(urlString + query);
        httpMethod = m;
        String contentType = request.getContentType();
        boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
        if (mp) {
            //------------ MULTPART POST ---------------
            List<Part> parts = new LinkedList<Part>();
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                parts.add(new StringPart(name, value));
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        parts.add(new StringPart(name, values[i]));
                    }
                }
            }
            m.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams()));
        } else {
            //------------ NORMAL POST ---------------
            // add internal props
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                m.addParameter(name, value);
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        m.addParameter(name, values[i]);
                    }
                }
            }
        }
    } else {
        log.error("Unsupported method ''{0}''", method);
        throw new IOException("Unsupported http method " + method);
    }
    log.debug("created http connection for method {0} to {1}", method, urlString + query);

    // add some request headers
    httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent"));
    httpMethod.setFollowRedirects(!isPost);
    httpMethod.getParams().setSoTimeout(soTimeout);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // send request
    httpClient.executeMethod(hostConfig, httpMethod, httpState);
    String contentType = httpMethod.getResponseHeader("Content-Type").getValue();

    log.debug("External app responded: {0}", httpMethod.getStatusLine());
    log.debug("External app contenttype: {0}", contentType);

    // check response code
    int statusCode = httpMethod.getStatusCode();
    if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) {
        PrintWriter writer = response.getWriter();
        writer.println("External application returned status code: " + statusCode);
        return;
    } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
        String location = httpMethod.getResponseHeader("Location").getValue();
        if (location == null) {
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
            return;
        }
        response.sendRedirect(rewriteURL(location, false));
        return;
    }

    // open input stream
    InputStream in = httpMethod.getResponseBodyAsStream();

    // check content type
    if (contentType != null && contentType.startsWith("text/html")) {
        rewriteHtml(in, contentType, response);
    } else {
        // binary mode
        if (contentType != null) {
            response.setContentType(contentType);
        }
        OutputStream outs = response.getOutputStream();

        try {
            byte buf[] = new byte[8192];
            int len;

            while ((len = in.read(buf)) != -1) {
                outs.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    HttpURLConnection urlConn;/* w w w  . ja  v a  2  s . com*/

    try {
        urlConn = (HttpURLConnection) url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setInstanceFollowRedirects(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", cookie);

        // send request
        urlConn.connect();

        // detect redirect
        int code = urlConn.getResponseCode();
        boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP;
        if (moved) {
            String location = urlConn.getHeaderField("Location");
            List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie");
            for (String val : headerVals) {
                if (val.startsWith(COOKIE))
                    cookie = val;
            }
            url = createRedirectUrl(location);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestProperty("Cookie", cookie);
        }

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line).append("\n");
        input.close();

        if (isLogDebugEnabled())
            logDebug("Response: " + response);

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e);
        return "";
    }
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

private void test302RedirectWithJetty(final String sendRedirectLocation, String expectedLocation,
        int httpsServerPortParameter) throws Exception {
    // SETUP//from w  ww . j av a 2  s.  c om
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    filterConfig.addInitParameter(XForwardedFilter.HTTPS_SERVER_PORT_PARAMETER,
            String.valueOf(httpsServerPortParameter));
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    HttpServlet mockServlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        public void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect(sendRedirectLocation);
        }

    };
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        httpURLConnection.setInstanceFollowRedirects(false);
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE
        Assert.assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, httpURLConnection.getResponseCode());
        String actualLocation = httpURLConnection.getHeaderField("Location");
        assertEquals(expectedLocation, actualLocation);

    } finally {
        server.stop();
    }
}

From source file:io.sloeber.core.managers.Manager.java

/**
 * copy a url locally taking into account redirections
 *
 * @param url/*from  www .j a va  2 s  .c o  m*/
 * @param localFile
 */
@SuppressWarnings("nls")
private static void myCopy(URL url, File localFile) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        conn.addRequestProperty("User-Agent", "Mozilla");
        conn.addRequestProperty("Referer", "google.com");

        // normally, 3xx is redirect
        int status = conn.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)

                Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(),
                        REPLACE_EXISTING);
        } else {
            Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING);
        }

    } catch (Exception e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e));
    }
}

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 av  a 2s .  c o  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();
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

private String getIconUrlWithHttpRedirect(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int statusCode = conn.getResponseCode();

    if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_SEE_OTHER) {
        return conn.getHeaderField("Location");
    } else {/*w  ww . jav  a 2s .c om*/
        return imageUrl;
    }
}

From source file:com.techventus.server.voice.Voice.java

/**
 * HTTP GET request for a given URL String.
 * /*  w  ww  . j av a2  s  . co m*/
 * @param urlString
 *            the url string
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
String get(String urlString) throws IOException {
    URL url = new URL(urlString);
    //+ "?auth=" + URLEncoder.encode(authToken, enc));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);
    conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(urlString + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
            || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
            || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) {
        redirectCounter++;
        if (redirectCounter > MAX_REDIRECTS) {
            redirectCounter = 0;
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Too manny redirects. exiting.");
        }
        String location = conn.getHeaderField("Location");
        if (location != null && !location.equals("")) {
            System.out.println(urlString + " - " + responseCode + " - new URL: " + location);
            return get(location);
        } else {
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Received moved answer but no Location. exiting.");
        }
    } else {
        is = conn.getErrorStream();
    }
    redirectCounter = 0;

    if (is == null) {
        throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                + ") : InputStream was null : exiting.");
    }

    String result = "";
    try {
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line + "\n\r");
        }
        rd.close();
        result = sb.toString();
    } catch (Exception e) {
        throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - "
                + e.getLocalizedMessage());
    }
    return result;
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

private String sendPostRequest(String urlAddress, String data, int redirects)
        throws MalformedURLException, IOException {
    String result = "";

    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }/*from  w  w w. j a va 2 s  . c  om*/
    URLConnection urlConnection = new URL(urlAddress).openConnection();

    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
    ((HttpURLConnection) urlConnection).setRequestMethod("POST");

    // Post JSON string to URL

    OutputStream os = urlConnection.getOutputStream();

    byte[] b = data.getBytes("UTF-8");

    os.write(b);

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendPostRequest(newUrlAddress, data, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    // Receive results back from API

    InputStream inStream = urlConnection.getInputStream();

    result = IOUtils.toString(inStream, "UTF-8");

    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }

    return result;
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

public String sendGetRequest(String urlAddress, int redirects) throws Exception {
    if (urlAddress.startsWith("https:")) {
        TrustManagerManipulator.allowAllSSL();
    }/*w  w w .j av  a2 s  .c  o m*/

    URL url = new URL(urlAddress);
    URLConnection urlConnection = url.openConnection();
    if (cookie != null)
        urlConnection.setRequestProperty("Cookie", cookie);
    if (apiKey != null)
        urlConnection.setRequestProperty("Cookie", apiKey);

    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    int status = ((HttpURLConnection) urlConnection).getResponseCode();
    // normally, 3xx is redirect
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            if (redirects <= 5) {
                String newUrlAddress = ((HttpURLConnection) urlConnection).getHeaderField("Location");
                if (null != newUrlAddress) {
                    return sendGetRequest(newUrlAddress, redirects + 1);
                }
            }
            //(else carry on, will exception out or something below)
        }
    } //TESTED

    //read back result
    BufferedReader inStream = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    StringBuilder strBuilder = new StringBuilder();
    String buffer;
    while ((buffer = inStream.readLine()) != null) {
        strBuilder.append(buffer);
    }
    inStream.close();

    //save cookie if cookie is null
    if (cookie == null) {
        String headername;
        for (int i = 1; (headername = urlConnection.getHeaderFieldKey(i)) != null; i++) {
            if (headername.equals("Set-Cookie")) {
                cookie = urlConnection.getHeaderField(i);
                break;
            }
        }
    }
    return strBuilder.toString();
}