Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:it.govpay.core.utils.client.BasicClient.java

private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl)
        throws ClientException {

    // Creazione Connessione
    int responseCode;
    HttpURLConnection connection = null;
    byte[] msg = null;
    GpContext ctx = GpThreadLocal.get();
    String urlString = url.toExternalForm();
    if (isAzioneInUrl) {
        if (!urlString.endsWith("/"))
            urlString = urlString.concat("/");
        try {/*from ww w. j  a v  a2  s  .c  om*/
            url = new URL(urlString.concat(azione));
        } catch (MalformedURLException e) {
            throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e);
        }
    }

    try {
        Message requestMsg = new Message();
        requestMsg.setType(MessageType.REQUEST_OUT);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        if (soap) {
            connection.setRequestProperty("SOAPAction", "\"" + azione + "\"");
            requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\""));
        }
        requestMsg.setContentType("text/xml");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestMethod("POST");

        // Imposta Contesto SSL se attivo
        if (sslContext != null) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
            httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
            HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled();
            httpsConn.setHostnameVerifier(disabilitato);
        }

        // Imposta l'autenticazione HTTP Basic se attiva
        if (ishttpBasicEnabled) {
            Base64 base = new Base64();
            String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes()));
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            requestMsg.addHeader(new Property("Authorization", "Basic " + encoding));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (soap) {
            SOAPUtils.writeMessage(body, header, baos);
        } else {
            JaxbUtils.marshal(body, baos);
        }

        ctx.getIntegrationCtx().setMsg(baos.toByteArray());
        invokeOutHandlers();

        if (log.getLevel().isMoreSpecificThan(Level.TRACE)) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getRequestProperties().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key));
            }
            sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg()));
            log.trace(sb.toString());
        }

        requestMsg.setContent(ctx.getIntegrationCtx().getMsg());

        ctx.getContext().getRequest().setOutDate(new Date());
        ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length));
        ctx.log(requestMsg);

        connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg());

    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        responseCode = connection.getResponseCode();
        ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode));

    } catch (Exception e) {
        throw new ClientException(e);
    }

    Message responseMsg = new Message();
    responseMsg.setType(MessageType.RESPONSE_IN);

    for (String key : connection.getHeaderFields().keySet()) {
        if (connection.getHeaderFields().get(key) != null) {
            if (key == null)
                responseMsg
                        .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0)));
            else if (connection.getHeaderFields().get(key).size() == 1)
                responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0)));
            else
                responseMsg.addHeader(
                        new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key))));
        }
    }

    try {
        if (responseCode < 300) {
            try {
                if (connection.getInputStream() == null) {
                    return null;
                }
                msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream())
                        : new byte[] {};
                if (msg.length > 0)
                    responseMsg.setContent(msg);
                return msg;
            } catch (Exception e) {
                throw new ClientException("Messaggio di risposta non valido", e);
            }
        } else {
            try {
                msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream())
                        : new byte[] {};
                responseMsg.setContent(msg);
            } catch (IOException e) {
                msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes();
            } finally {
                log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode
                        + "]\nRisposta: " + new String(msg));
            }

            throw new ClientException("Ricevuto [HTTP " + responseCode + "]");
        }
    } finally {
        if (responseMsg != null) {
            ctx.getContext().getResponse().setInDate(new Date());
            ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length);
            ctx.log(responseMsg);
        }

        if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null
                && connection.getHeaderFields() != null) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getHeaderFields().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getHeaderField(key));
            }
            sb.append("\n" + new String(msg));
            log.trace(sb.toString());
        }
    }

}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title,
        String description, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//from  w  ww  . j a  v  a 2s  .c o  m
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    // urlConnection.setRequestProperty("Content-Length", newValue);
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData = null;

    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    String template = readFile(activity, R.raw.gdata).toString();

    // Workarounds for corner cases. Youtube doesnt like empty titles
    if (title == null || title.length() == 0) {
        title = "Untitled";
    }
    if (description == null || description.length() == 0) {
        description = "No description";
    }

    atomData = String.format(template, title, description, category, this.tags);

    OutputStreamWriter outStreamWriter = null;
    int responseCode = -1;

    try {
        outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
        outStreamWriter.write(atomData);
        outStreamWriter.close();

        /*
         * urlConnection.connect(); InputStream is =
         * urlConnection.getInputStream(); BufferedReader in = new
         * BufferedReader(new InputStreamReader(is)); String inputLine;
         * 
         * while ((inputLine = in.readLine()) != null) {
         * Log.d(TAG,inputLine); } in.close();
         */

        responseCode = urlConnection.getResponseCode();

        // ERROR LOGGING
        InputStream is = urlConnection.getErrorStream();
        if (is != null) {
            Log.e(TAG, " Error stream from Youtube available!");
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, inputLine);
            }
            in.close();

            Map<String, List<String>> hfs = urlConnection.getHeaderFields();
            for (Entry<String, List<String>> hf : hfs.entrySet()) {
                Log.d(TAG, " entry : " + hf.getKey());
                List<String> vals = hf.getValue();
                for (String s : vals) {
                    Log.d(TAG, "vals:" + s);
                }
            }
        }

    } catch (IOException e) {
        //
        // Catch IO Exceptions here, like UnknownHostException, so we can
        // detect network failures, and send a notification
        //
        Log.d(TAG, " Error occured in uploadMetaData! ");
        e.printStackTrace();
        responseCode = -1;
        outStreamWriter = null;

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((SSCXferActivity) activity).finishedUploading(false);
                ((SSCXferActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

            }
        }, 0);

        // forward it on!
        throw e;
    }

    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(activity, handler, filePath, title, description, false);
        } else {

            // Probably not authorised!

            // Need to setup a Youtube account.

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(false);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));

        }
    }

    return urlConnection.getHeaderField("Location");
}

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/* ww w  .j  a  v a  2  s  .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:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title,
        String description, boolean retry, long sdrecord_id) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//from  w  ww .  j a va  2  s .c  o m
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    // urlConnection.setRequestProperty("Content-Length", newValue);
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData = null;

    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    String template = readFile(activity, R.raw.gdata).toString();

    // Workarounds for corner cases. Youtube doesnt like empty titles
    if (title == null || title.length() == 0) {
        title = "Untitled";
    }
    if (description == null || description.length() == 0) {
        description = "No description";
    }

    // Check user preference to see if YouTube videos should be private by
    // default.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
    Boolean ytPrivate = prefs.getBoolean("defaultYouTubePrivatePreference", true);

    String private_or_not = "<yt:private />";
    if (!ytPrivate) {
        private_or_not = "";
    }

    atomData = String.format(template, title, description, category, this.tags, private_or_not);

    OutputStreamWriter outStreamWriter = null;
    int responseCode = -1;

    try {
        outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
        outStreamWriter.write(atomData);
        outStreamWriter.close();

        /*
         * urlConnection.connect(); InputStream is =
         * urlConnection.getInputStream(); BufferedReader in = new
         * BufferedReader(new InputStreamReader(is)); String inputLine;
         * 
         * while ((inputLine = in.readLine()) != null) {
         * Log.d(TAG,inputLine); } in.close();
         */

        responseCode = urlConnection.getResponseCode();

        // ERROR LOGGING
        InputStream is = urlConnection.getErrorStream();
        if (is != null) {
            Log.e(TAG, " Error stream from Youtube available!");
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                Log.d(TAG, inputLine);
            }
            in.close();

            Map<String, List<String>> hfs = urlConnection.getHeaderFields();
            for (Entry<String, List<String>> hf : hfs.entrySet()) {
                Log.d(TAG, " entry : " + hf.getKey());
                List<String> vals = hf.getValue();
                for (String s : vals) {
                    Log.d(TAG, "vals:" + s);
                }
            }
        }

    } catch (IOException e) {
        //
        // Catch IO Exceptions here, like UnknownHostException, so we can
        // detect network failures, and send a notification
        //
        Log.d(TAG, " Error occured in uploadMetaData! ");
        e.printStackTrace();
        responseCode = -1;
        outStreamWriter = null;

        mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

        // Use the handler to execute a Runnable on the
        // main thread in order to have access to the
        // UI elements.
        handler.postDelayed(new Runnable() {
            public void run() {
                // Update UI

                // Indicate back to calling activity the result!
                // update uploadInProgress state also.

                ((VidiomActivity) activity).finishedUploading(false);
                ((VidiomActivity) activity)
                        .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

            }
        }, 0);

        // forward it on!
        throw e;
    }

    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(activity, handler, filePath, title, description, false, sdrecord_id);
        } else {

            mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_YT);

            // Probably not authorised!

            // Need to setup a Youtube account.

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((VidiomActivity) activity).finishedUploading(false);
                    ((VidiomActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_youtube_host_failed_));

                }
            }, 0);

            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));

        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataExt(JSONObject obj) {
    String requestUrl;/*from www . j  a  v a2s. co m*/
    String id;
    String method;
    String body;
    String headers;
    try {
        //Request url
        requestUrl = obj.getString("url");

        //ID that correlates the request to the event
        id = obj.getString("id");

        //Request method
        method = obj.getString("method");

        //Request body
        body = obj.getString("body");

        //Request header
        headers = obj.getString("headers");

        String js = null;
        if (method == null || method.length() == 0)
            method = "GET";

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        boolean forceUTF8 = false;

        try {
            if (headers.length() > 0) {
                String[] headerArray = headers.split("&");

                //Set request header
                for (String header : headerArray) {
                    String[] headerPair = header.split("=");
                    if (headerPair.length == 2) {
                        String field = headerPair[0];
                        String value = headerPair[1];
                        if (field != null && value != null) {
                            if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request
                                connection.setRequestProperty(field, value);
                            }

                            field = field.toLowerCase();
                            value = value.toLowerCase();
                            if (field.equals("content-type") && value.indexOf("charset") > -1
                                    && value.indexOf("utf-8") > -1) {
                                forceUTF8 = true;
                            }
                        }
                    }
                }

            }

            if ("POST".equalsIgnoreCase(method)) {
                connection.setRequestMethod(method);
                connection.setDoOutput(true);
                connection.setFixedLengthStreamingMode(body.length());
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(body);
                dStream.flush();
                dStream.close();
            }

            //inject response
            int statusCode = connection.getResponseCode();

            final StringBuilder response = new StringBuilder();
            try {
                InputStream responseStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();
            } catch (Exception e) {
            }

            String responseBody = null;
            // how to handle UTF8 without EntityUtils?
            //                if (forceUTF8) {
            //                    responseBody = EntityUtils.toString(entity, "UTF-8");
            //                } else {
            //                    responseBody = EntityUtils.toString(entity);
            //                }
            responseBody = response.toString();
            String responseMessage = connection.getResponseMessage();

            char[] bom = { 0xef, 0xbb, 0xbf };
            //check for BOM characters, then strip if present
            if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0]
                    && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) {
                responseBody = responseBody.substring(3);
            }

            //escape existing backslashes
            responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\");

            //escape internal double-quotes
            responseBody = responseBody.replaceAll("\"", "\\\\\"");
            responseBody = responseBody.replaceAll("'", "\\\\'");

            //replace linebreaks with \n
            responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

            StringBuilder extras = new StringBuilder("{");
            extras.append(String.format("status:'%d',", statusCode));

            String status = null;
            switch (statusCode) {
            case 200:
                status = "OK";
                break;
            case 201:
                status = "CREATED";
                break;
            case 202:
                status = "Accepted";
                break;
            case 203:
                status = "Partial Information";
                break;
            case 204:
                status = "No Response";
                break;
            case 301:
                status = "Moved";
                break;
            case 302:
                status = "Found";
                break;
            case 303:
                status = "Method";
                break;
            case 304:
                status = "Not Modified";
                break;
            case 400:
                status = "Bad request";
                break;
            case 401:
                status = "Unauthorized";
                break;
            case 402:
                status = "PaymentRequired";
                break;
            case 403:
                status = "Forbidden";
                break;
            case 404:
                status = "Not found";
                break;
            case 500:
                status = "Internal Error";
                break;
            case 501:
                status = "Not implemented";
                break;
            case 502:
                status = "Service temporarily overloaded";
                break;
            case 503:
                status = "Gateway timeout";
                break;
            }
            extras.append(String.format("statusText:'%s',", status));
            extras.append("headers: {");

            List<String> cookieData = new ArrayList<String>();
            Map<String, List<String>> allHeaders = connection.getHeaderFields();
            for (String key : allHeaders.keySet()) {
                if (key == null) {
                    continue;
                }
                String value = connection.getHeaderField(key);
                value = value.replaceAll("'", "\\\\'");
                if (key.toLowerCase().equals("set-cookie"))
                    cookieData.add(value);
                else
                    extras.append(String.format("'%s':'%s',", key, value));
            }

            String concatCookies = cookieData.toString();
            concatCookies = concatCookies.substring(0, concatCookies.length());
            extras.append(String.format("'Set-Cookie':'%s',",
                    concatCookies.substring(1, concatCookies.length() - 1)));

            String cookieArray = "[";
            for (int i = 0; i < cookieData.size(); i++)
                cookieArray += String.format("'%s',", cookieData.get(i));
            cookieArray += "]";

            extras.append("'All-Cookies': " + cookieArray);
            extras.append("} }");

            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);",
                    id, responseBody, extras.toString());

        } catch (Exception ex) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, ex.getMessage());
        } catch (OutOfMemoryError err) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, err.getMessage());
        } finally {
            connection.disconnect();
        }

        injectJS(js);

    } catch (Exception e) {
        Log.d("getRemoteDataExt", e.getMessage());
    }
}

From source file:org.opendaylight.vtn.manager.it.northbound.VtnNorthboundIT.java

/**
 * Send request and get result// w  ww .j a  v  a2  s .  c om
 *
 * @param restUrl   A request URL.
 * @param method    A request method.
 * @param body      A request body send with request.
 * @param contentType A contentType of request.
 * @param auth      if {@code true} authorization succeed,
 *                  else if {@code false} authorization fails.
 * @return  A returned result for request.
 */
private String getJsonResult(String restUrl, String method, String body, String contentType, boolean auth) {

    // Initialize response code to indicate error
    httpResponseCode = HTTP_BAD_REQUEST;
    httpLocation = null;

    LOG.debug("HTTP method: {}, uri: {}", method, restUrl);
    LOG.debug("Body: {}", body);

    try {
        URL url = new URL(restUrl);
        this.userManager.getAuthorizationList();
        String authString = null;
        if (auth) {
            this.userManager.authenticate("admin", "admin");
            authString = "admin:admin";
        } else {
            this.userManager.authenticate("admin", "bad");
            authString = "admin:bad";
        }
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Accept", "application/json");

        if (body != null) {
            connection.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(body);
            wr.flush();
        }
        connection.connect();
        connection.getContentType();

        // Response code for success should be 2xx
        httpResponseCode = connection.getResponseCode();
        LOG.debug("HTTP response code: {}", httpResponseCode);
        LOG.debug("HTTP response message: {}", connection.getResponseMessage());

        if (httpResponseCode == HTTP_CREATED) {
            // Determine location.
            for (int i = 0; true; i++) {
                String field = connection.getHeaderFieldKey(i);
                if (field == null) {
                    if (i == 0) {
                        continue;
                    }
                    break;
                }

                if (field.equalsIgnoreCase("location")) {
                    httpLocation = connection.getHeaderField(i);
                    break;
                }
            }
        }

        boolean error = (httpResponseCode > 299);
        InputStream is = (error) ? connection.getErrorStream() : connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (is != null) {
            InputStreamReader in = new InputStreamReader(is, Charset.forName("UTF-8"));
            BufferedReader rd = new BufferedReader(in);
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            is.close();
        }
        connection.disconnect();

        if (httpResponseCode > 299) {
            String msg = sb.toString();
            if (msg.length() != 0) {
                LOG.debug("HTTP error response body: {}", msg);
                return msg;
            }
            return httpResponseCode.toString();
        }

        if (httpResponseCode == HTTP_NO_CONTENT) {
            assertEquals(0, sb.length());
        }

        return sb.toString();
    } catch (Exception e) {
        LOG.error("Caught exception.", e);
        return null;
    }
}

From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest req = context.getHreq();
    HttpServletResponse res = context.getHres();

    String requestURI = getRequestURI(req);
    String qs = req.getQueryString();
    if (qs != null) {
        requestURI = new StringBuffer(requestURI).append("?").append(qs).toString();
    }//from ww w  . j  a  v a 2 s  .  c  o  m

    URL url = null;
    try {
        url = new URL("http", uri.getHost(), uri.getPort(), requestURI);
        if (_log.isTraceEnabled())
            _log.trace("proxying to: " + url);
    } catch (MalformedURLException e) {
        if (_log.isWarnEnabled())
            _log.warn("bad proxy url: " + url, e);
        throw new IrrecoverableException("bad proxy url", e);
    }

    long startTime = System.currentTimeMillis();

    HttpURLConnection huc = null;
    String m = req.getMethod();
    try {
        huc = (HttpURLConnection) url.openConnection(); // IOException
        huc.setRequestMethod(m); // ProtocolException
    } catch (ProtocolException e) {
        if (_log.isWarnEnabled())
            _log.warn("unsupported http method: " + m, e);
        throw new IrrecoverableException("unsupported HTTP method: " + m, e);
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy IO problem", e);
        throw new RecoverableException("could not open proxy connection", e);
    }

    huc.setAllowUserInteraction(false);
    huc.setInstanceFollowRedirects(false);

    // check connection header
    // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers - inefficient, but we are constrained by servlet API
    {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String hdr = (String) e.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ?
                continue;
            // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option
            if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header...
                continue; // strip this out - we may be being spoofed

            for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) {
                String val = (String) f.nextElement();
                if (val != null) {
                    huc.addRequestProperty(hdr, val);
                }
            }
        }
    }

    // content ?
    boolean hasContent = false;
    {
        int contentLength = 0;
        String tmp = huc.getRequestProperty("Content-Length");
        if (tmp != null) {
            try {
                contentLength = Integer.parseInt(tmp);
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }

        if (contentLength > 0)
            hasContent = true;
        else
            hasContent = (huc.getRequestProperty("Content-Type") != null);
    }

    // proxy
    {
        huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ?
        huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain...
        // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ?
    }

    // cache-control
    {
        String cacheControl = huc.getRequestProperty("Cache-Control");
        if (cacheControl != null
                && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0))
            huc.setUseCaches(false);
    }

    // confidentiality
    {
        if (req.isSecure()) {
            huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString());
        }

        // at the other end, if this header is present we must :

        // wrap the request so that req.isSecure()=true, before processing...
        // mask the header - so it is never seen by the app.

        // the code for the other end should live in this class.

        // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member...
    }
    // customize Connection
    huc.setDoInput(true);

    // client->server
    int client2ServerTotal = 0;
    {
        if (hasContent) {
            huc.setDoOutput(true);

            OutputStream toServer = null;
            try {
                InputStream fromClient = req.getInputStream(); // IOException
                toServer = huc.getOutputStream(); // IOException
                client2ServerTotal = copy(fromClient, toServer, 8192);
            } catch (IOException e) {
                new IrrecoverableException("problem proxying client request to server", e);
            } finally {
                if (toServer != null) {
                    try {
                        toServer.close(); // IOException
                    } catch (IOException e) {
                        _log.warn("problem closing server request stream", e);
                    }
                }
            }
        }
    }

    // Connect
    try {
        huc.connect(); // IOException
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy connection problem: " + url, e);
        throw new RecoverableException("could not connect to proxy target", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 0;
    if (huc == null) {
        try {
            fromServer = huc.getInputStream(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring client output", e);
        }
    } else {
        code = 502;
        //         String message="Bad Gateway: could not read server response code or message";
        try {
            code = huc.getResponseCode(); // IOException
            //            message=huc.getResponseMessage(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring http server response code/message", e);
        } finally {
            //            res.setStatus(code, message); - deprecated
            res.setStatus(code);
        }

        if (code < 400) {
            // 1XX:continue, 2XX:successful, 3XX:multiple-choices...
            try {
                fromServer = huc.getInputStream(); // IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem acquiring http client output", e);
            }
        } else {
            // 4XX:client, 5XX:server error...
            fromServer = huc.getErrorStream(); // why does this not throw IOException ?
            // TODO - do we need to use sendError()?
        }
    }

    // clear response defaults.
    res.setHeader("Date", null);
    res.setHeader("Server", null);

    // set response headers
    if (false) {
        int h = 0;
        String hdr = huc.getHeaderFieldKey(h);
        String val = huc.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = (hdr != null) ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                res.addHeader(hdr, val);

            // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val);

            h++;
            hdr = huc.getHeaderFieldKey(h);
            val = huc.getHeaderField(h);
        }
    } else {
        // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
        // Try this inside Tomcat...
        String key;
        for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) {
            key = key.toLowerCase();
            String val = huc.getHeaderField(i);
            if (val != null && !_DontProxyHeaders.contains(key)) {
                res.addHeader(key, val);
            }
        }
    }

    // do we need another Via header in the response...

    // server->client
    int server2ClientTotal = 0;
    {
        if (fromServer != null) {
            try {
                OutputStream toClient = res.getOutputStream();// IOException
                server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem proxying server response back to client", e);
            } finally {
                try {
                    fromServer.close();
                } catch (IOException e) {
                    // well - we did our best...
                    _log.warn("problem closing server response stream", e);
                }
            }
        }
    }

    huc.disconnect();

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled())
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", url:" + url);
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request
 * and return the result.//  w  ww  .ja va2s  .  c om
 * 
 * @param context
 *            The context to use for this operation. Used to generate the
 *            user agent if needed.
 * @param urlValue
 *            The webservice URL.
 * @param method
 *            The request method to use.
 * @param parameterList
 *            The parameters to add to the request.
 * @param headerMap
 *            The headers to add to the request.
 * @param isGzipEnabled
 *            Whether the request will use gzip compression if available on
 *            the server.
 * @param userAgent
 *            The user agent to set in the request. If null, a default
 *            Android one will be created.
 * @param postText
 *            The POSTDATA text to add in the request.
 * @param credentials
 *            The credentials to use for authentication.
 * @param isSslValidationEnabled
 *            Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, String contentType, List<byte[]> fileByteDates,
        List<String> fileMimeTypes, int httpErrorResCodeFilte, boolean isMulFiles) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // ?
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0 && NetworkConnection.CT_DEFALUT.equals(contentType)) { // form
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE,
                // "application/x-www-form-urlencoded");
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, contentType);
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null && (NetworkConnection.CT_JSON.equals(contentType)
                    || NetworkConnection.CT_XML.equals(contentType))) { // body
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE, "application/json");
                // //add ?json???
                headerMap.put(HTTP.CONTENT_TYPE, contentType); // add
                // ?json???
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(postText.getBytes().length));
                outputText = postText;
                // Log.e("newtewewerew",
                // "1111application/json------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
                // );
            } else if (NetworkConnection.CT_MULTIPART.equals(contentType)) { // 
                String[] Array = urlValue.split("/");
                /*Boolean isFiles = false;
                if (Array[Array.length - 1].equals("clientRemarkPic")) {
                   isFiles = true;
                }*/
                if (null == fileByteDates || fileByteDates.size() <= 0) {
                    throw new ConnectionException("file formdata no bytes data",
                            NetworkConnection.EXCEPTION_CODE_FORMDATA_NOBYTEDATE);
                }
                headerMap.put(HTTP.CONTENT_TYPE, contentType + ";boundary=" + BOUNDARY);
                String bulidFormText = bulidFormText(parameterList);
                bos.write(bulidFormText.getBytes());
                for (int i = 0; i < fileByteDates.size(); i++) {
                    long currentTimeMillis = System.currentTimeMillis();
                    StringBuffer sb = new StringBuffer("");
                    sb.append(PREFIX).append(BOUNDARY).append(LINEND);
                    // sb.append("Content-Type:application/octet-stream" +
                    // LINEND);
                    // sb.append("Content-Disposition: form-data; name=\""+nextInt+"\"; filename=\""+nextInt+".png\"").append(LINEND);;
                    if (isMulFiles)
                        sb.append("Content-Disposition: form-data; name=\"files\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    else
                        sb.append("Content-Disposition: form-data; name=\"file\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append("Content-Type:" + fileMimeTypes.get(i) + LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append(LINEND);
                    bos.write(sb.toString().getBytes());
                    bos.write(fileByteDates.get(i));
                    bos.write(LINEND.getBytes());
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
                bos.write(end_data);
                bos.flush();
                headerMap.put(HTTP.CONTENT_LEN, bos.size() + "");
            }
            // L.e("newtewewerew",
            // "2222------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
            // );
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);
        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT)) {
            OutputStream output = null;
            try {
                if (NetworkConnection.CT_MULTIPART.equals(contentType)) {
                    output = connection.getOutputStream();
                    output.write(bos.toByteArray());
                } else {
                    if (null != outputText) {
                        L.e("newtewewerew", method + "------------------outputText:::" + outputText);
                        output = connection.getOutputStream();
                        output.write(outputText.getBytes());
                    }
                }

            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing
                        // to do here.
                    }
                }
            }
        }

        // Log the request
        if (L.canLog(Log.DEBUG)) {
            L.d(TAG, "Request url: " + urlValue);
            L.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                L.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    L.d(TAG, message);
                }
                L.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                L.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                L.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    L.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        L.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            // L.e("responseCode:"+responseCode+" httpErrorResCodeFilte:"+httpErrorResCodeFilte+" responseCode==httpErrorResCodeFilte:"+(responseCode==httpErrorResCodeFilte));
            if (responseCode == httpErrorResCodeFilte) { // 400???...
                logResBodyAndHeader(connection, error);
                return new ConnectionResult(connection.getHeaderFields(), error, responseCode);
            } else {
                throw new ConnectionException(error, responseCode);
            }
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        // ?? ?
        if (null != body && body.contains("\r")) {
            body = body.replace("\r", "");
        }

        if (null != body && body.contains("\n")) {
            body = body.replace("\n", "");
        }

        logResBodyAndHeader(connection, body);

        return new ConnectionResult(connection.getHeaderFields(), body, responseCode);
    } catch (IOException e) {
        L.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        L.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        L.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc/*from ww  w . java2s. c o m*/
 */
public String[] getHeaderFields(String name, Object connection) throws IOException {
    HttpURLConnection c = (HttpURLConnection) connection;
    List<String> headers = new ArrayList<String>();

    // we need to merge headers with differing case since this should be case insensitive
    for (String key : c.getHeaderFields().keySet()) {
        if (key != null && key.equalsIgnoreCase(name)) {
            headers.addAll(c.getHeaderFields().get(key));
        }
    }
    if (headers.size() > 0) {
        List<String> v = new ArrayList<String>();
        v.addAll(headers);
        Collections.reverse(v);
        String[] s = new String[v.size()];
        v.toArray(s);
        return s;
    }
    // workaround for a bug in some android devices
    String f = c.getHeaderField(name);
    if (f != null && f.length() > 0) {
        return new String[] { f };
    }
    return null;

}