Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:cgeo.geocaching.cgBase.java

public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) {
    if (app == null) {
        return;//from   w ww.j  a  v  a 2s .c om
    }
    if (settings == null || StringUtils.isBlank(settings.tokenPublic)
            || StringUtils.isBlank(settings.tokenSecret)) {
        return;
    }

    try {
        Map<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (coords != null) {
            parameters.put("lat", String.format("%.6f", coords.getLatitude()));
            parameters.put("long", String.format("%.6f", coords.getLongitude()));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//from   w w  w .  ja  v a2  s  .  c  o  m
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.irccloud.android.NetworkConnection.java

public String fetch(URL url, String postdata, String sk, String token, HashMap<String, String> headers)
        throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;/*from w ww. j ava  2  s . com*/
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
        if (url.getHost().equals(IRCCLOUD_HOST))
            https.setSSLSocketFactory(IRCCloudSocketFactory);
        conn = https;
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setUseCaches(false);
    conn.setRequestProperty("User-Agent", useragent);
    conn.setRequestProperty("Accept", "application/json");
    if (headers != null) {
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key, headers.get(key));
        }
    }
    if (sk != null)
        conn.setRequestProperty("Cookie", "session=" + sk);
    if (token != null)
        conn.setRequestProperty("x-auth-formtoken", token);
    if (postdata != null) {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        OutputStream ostr = null;
        try {
            ostr = conn.getOutputStream();
            ostr.write(postdata.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ostr != null)
                ostr.close();
        }
    }
    BufferedReader reader = null;
    String response = "";

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi");
        } else {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile");
        }
    } catch (Exception e) {
    }

    try {
        if (conn.getInputStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
        }
    } catch (IOException e) {
        if (conn.getErrorStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
        }
    }

    if (reader != null) {
        response = toString(reader);
        reader.close();
    }
    conn.disconnect();
    return response;
}

From source file:com.pras.conn._HttpConHandler.java

/**
 * @param urlStr HTTP URL/*from   w ww  .  j  a v  a 2  s .  c  o  m*/
 * @param type Type of Connection (POST, GET, PUT or DELETE)
 * @param httpHeaders HTTP headers
 * @param postData Data to be sent as a part of POST/PUT request
 * 
 * @return ATOM XML feed and Response/Error message
 */
public Response doConnect(String urlStr, int type, HashMap<String, String> httpHeaders, String postData) {

    String res = null;
    HttpURLConnection con = null;
    Response response = new Response();
    String TAG = "HttpConHandler";

    try {
        /*
         * IMPORTANT: 
         * User SHOULD provide URL Encoded Parms
         */
        Log.enableLog();
        Log.p(TAG, "URL=" + urlStr);

        // Somehow Eclipse is not detecting Proxy
        // HTTP Proxy
        //         System.getProperties().put("http.proxyHost", "168.219.61.250");
        //         System.getProperties().put("http.proxyPort", "8080");
        // HTTPS Proxy
        //         System.getProperties().put("https.proxyHost", "168.219.61.252");
        //         System.getProperties().put("https.proxyPort", "8080");
        // TODO: Remove proxy
        // DROCA Initialisation du Proxy
        Log.p(TAG, "doConnect init proxy");
        Proxy proxy = Proxy.NO_PROXY;
        proxy = getProxy();
        //         Log.p(TAG, "doConnect new URL BEFORE");
        URL url = new URL(urlStr);
        //         Log.p(TAG, "doConnect new URL AFTER");
        //         Log.p(TAG, "doConnect url.openConnection BEFORE");
        con = (HttpURLConnection) url.openConnection(proxy);
        Log.p(TAG, "doConnect url.openConnection AFTER");
        //
        //         URL url = new URL(urlStr);
        //         con = (HttpURLConnection) url.openConnection();

        //con.setInstanceFollowRedirects(false);

        OutputStream out = null;

        // Set headers
        /*
         * All subsequent request to Google Spreadsheet/Data API
         * should include following 2 Headers
         */
        //con.setRequestProperty("Authorization", "GoogleLogin auth="+ authToken);
        //con.setRequestProperty("GData-Version", "3.0");

        if (httpHeaders != null) {
            Log.p(TAG, "Number of HTTP Headers: " + httpHeaders.size());
            Iterator<String> keys = httpHeaders.keySet().iterator();
            while (keys.hasNext()) {
                String k = keys.next();
                con.setRequestProperty(k, httpHeaders.get(k));
            }
        }

        Log.p(TAG, "doConnect type:" + type);
        if (type == HTTP_POST) {
            //            Log.p(TAG, "doConnect HTTP_POST 1");
            con.setDoOutput(true);
            //            Log.p(TAG, "doConnect HTTP_POST 2");
            out = con.getOutputStream();
            //            Log.p(TAG, "doConnect HTTP_POST 3");
            out.write(postData.getBytes());
            //            Log.p(TAG, "doConnect HTTP_POST 4");
            out.flush();
            //            Log.p(TAG, "doConnect HTTP_POST 5");
        } else if (type == HTTP_GET) {
            //            Log.p(TAG, "doConnect HTTP_GET 1");
            con.setDoInput(true);
            //            Log.p(TAG, "doConnect HTTP_GET 2");
        } else if (type == HTTP_DELETE) {
            //            Log.p(TAG, "doConnect HTTP_DELETE 1");
            con.setRequestMethod("DELETE");
            //            Log.p(TAG, "doConnect HTTP_DELETE 2");
            con.connect();
            //            Log.p(TAG, "doConnect HTTP_DELETE 3");
        } else if (type == HTTP_PUT) {
            //            Log.p(TAG, "doConnect HTTP_PUT 1");
            con.setRequestMethod("PUT");
            //            Log.p(TAG, "doConnect HTTP_PUT 2");
            // Send Data
            con.setDoOutput(true);
            //            Log.p(TAG, "doConnect HTTP_PUT 3");
            out = con.getOutputStream();
            //            Log.p(TAG, "doConnect HTTP_PUT 4");
            out.write(postData.getBytes());
            //            Log.p(TAG, "doConnect HTTP_PUT 5");
            out.flush();
            //            Log.p(TAG, "doConnect HTTP_PUT 6");
        }

        // Read Response Code
        //         Log.p(TAG, "doConnect response.setResponseCode con.getResponseCode():"+con.getResponseCode()+" BEFORE");
        response.setResponseCode("" + con.getResponseCode());
        //         Log.p(TAG, "doConnect response.setResponseCode AFTER");
        //         Log.p(TAG, "doConnect response.setResponseCode con.setResponseMessage():"+con.getResponseMessage()+" BEFORE");
        response.setResponseMessage(con.getResponseMessage());
        //         Log.p(TAG, "doConnect response.setResponseCode AFTER");

        // Read InputStream
        //         Log.p(TAG, "doConnect response.setResponseCode con.getInputStream BEFORE");
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //         Log.p(TAG, "doConnect response.setResponseCode con.getInputStream AFTER");
        StringBuffer strBuf = new StringBuffer();
        String line = "";
        //         Log.p(TAG, "doConnect response.setResponseCode reader.readLine() BEFORE");
        try {
            while ((line = reader.readLine()) != null) {
                //               Log.p(TAG, "doConnect response.setResponseCode reader.readLine() line:"+line);
                strBuf.append(line);
            }
        }
        // DROCA : Pour contourner une erreur (pb genere quant connexion via proxy)
        // Message : [HttpConHandler] Error in reading response: java.net.SocketException: Socket is closed
        catch (Exception ex) {
            Log.p(TAG, "Error in reading response: " + ex.toString());
        }
        //         Log.p(TAG, "doConnect response.setResponseCode reader.readLine() AFTER");

        //         Log.p(TAG, "doConnect response.setResponseCode reader.close() BEFORE");
        reader.close();
        //         Log.p(TAG, "doConnect response.setResponseCode reader.close() AFTER");

        if (out != null)
            out.close();

        res = strBuf.toString();

        response.setOutput(res);

        Log.p(TAG, "Response from Google Server: \n" + res);

    } catch (Exception ex) {

        Log.p(TAG, "Error in connection: " + ex.toString());
        // Oops Exception
        response.setError(true);

        // Set Exception
        response.setException(ex);

        if (con == null)
            return response;

        InputStream error_in = con.getErrorStream();

        if (error_in == null)
            return response;

        // Read the error stream
        BufferedReader reader = new BufferedReader(new InputStreamReader(error_in));
        if (reader == null)
            return response;

        StringBuffer errStrBuf = new StringBuffer();
        String line = "";

        try {
            while ((line = reader.readLine()) != null)
                errStrBuf.append(line);

            // Set Error Stream Message
            response.setErrorStreamMsg(errStrBuf.toString());

            reader.close();

            // Display error on logging console
            response.printErrorLog();

        } catch (Exception e) {
            Log.p(TAG, "Error in reading Stream: " + e.getMessage());
        }
    }
    return response;
}

From source file:com.diablominer.DiabloMiner.NetworkState.JSONRPCNetworkState.java

JsonNode doJSONRPCCall(boolean longPoll, ObjectNode message) throws IOException {
    HttpURLConnection connection = null;
    try {/*from   w w w.j  a  v a 2s  .  c  o m*/
        URL url;

        if (longPoll)
            url = longPollUrl;
        else
            url = queryUrl;

        Proxy proxy = diabloMiner.getProxy();

        if (proxy == null)
            connection = (HttpURLConnection) url.openConnection();
        else
            connection = (HttpURLConnection) url.openConnection(proxy);

        if (longPoll) {
            connection.setConnectTimeout(10 * 60 * 1000);
            connection.setReadTimeout(10 * 60 * 1000);
        } else {
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(15 * 1000);
        }

        connection.setRequestProperty("Authorization", userPass);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("User-Agent", "DiabloMiner");
        connection.setRequestProperty("X-Mining-Extensions", "longpoll rollntime switchto");
        connection.setDoOutput(true);

        OutputStream requestStream = connection.getOutputStream();
        Writer request = new OutputStreamWriter(requestStream);
        request.write(message.toString());
        request.close();
        requestStream.close();

        ObjectNode responseMessage = null;

        InputStream responseStream = null;

        try {
            String xLongPolling = connection.getHeaderField("X-Long-Polling");

            if (xLongPolling != null && !"".equals(xLongPolling) && longPollAsync == null) {
                if (xLongPolling.startsWith("http"))
                    longPollUrl = new URL(xLongPolling);
                else if (xLongPolling.startsWith("/"))
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            xLongPolling);
                else
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            (url.getFile() + "/" + xLongPolling).replace("//", "/"));

                longPollAsync = new LongPollAsync();
                Thread thread = new Thread(longPollAsync,
                        "DiabloMiner JSONRPC LongPollAsync for " + url.getHost());
                thread.start();
                diabloMiner.addThread(thread);

                workLifetime = 60000;

                diabloMiner.debug(queryUrl.getHost() + ": Enabling long poll support");
            }

            String xRollNTime = connection.getHeaderField("X-Roll-NTime");

            if (xRollNTime != null && !"".equals(xRollNTime)) {
                if (!"n".equalsIgnoreCase(xRollNTime) && rollNTime == false) {
                    rollNTime = true;

                    if (xRollNTime.startsWith("expire=")) {
                        try {
                            workLifetime = Integer.parseInt(xRollNTime.substring(7)) * 1000;
                        } catch (NumberFormatException ex) {
                        }
                    } else {
                        workLifetime = 60000;
                    }

                    diabloMiner.debug(queryUrl.getHost() + ": Enabling roll ntime support, expire after "
                            + (workLifetime / 1000) + " seconds");
                } else if ("n".equalsIgnoreCase(xRollNTime) && rollNTime == true) {
                    rollNTime = false;

                    if (longPoll)
                        workLifetime = 60000;
                    else
                        workLifetime = diabloMiner.getWorkLifetime();

                    diabloMiner.debug(queryUrl.getHost() + ": Disabling roll ntime support");
                }
            }

            String xSwitchTo = connection.getHeaderField("X-Switch-To");

            if (xSwitchTo != null && !"".equals(xSwitchTo)) {
                String oldHost = queryUrl.getHost();
                JsonNode newHost = mapper.readTree(xSwitchTo);

                queryUrl = new URL(queryUrl.getProtocol(), newHost.get("host").asText(),
                        newHost.get("port").getIntValue(), queryUrl.getPath());

                if (longPollUrl != null)
                    longPollUrl = new URL(longPollUrl.getProtocol(), newHost.get("host").asText(),
                            newHost.get("port").getIntValue(), longPollUrl.getPath());

                diabloMiner.info(oldHost + ": Switched to " + queryUrl.getHost());
            }

            String xRejectReason = connection.getHeaderField("X-Reject-Reason");

            if (xRejectReason != null && !"".equals(xRejectReason)) {
                rejectReason = xRejectReason;
            }

            String xIsP2Pool = connection.getHeaderField("X-Is-P2Pool");

            if (xIsP2Pool != null && !"".equals(xIsP2Pool)) {
                if (!noDelay)
                    diabloMiner.info("P2Pool no delay mode enabled");

                noDelay = true;
            }

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    responseStream = new GZIPInputStream(connection.getInputStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    responseStream = new InflaterInputStream(connection.getInputStream());
            } else {
                responseStream = connection.getInputStream();
            }

            if (responseStream == null)
                throw new IOException("Drop to error handler");

            Object output = mapper.readTree(responseStream);

            if (NullNode.class.equals(output.getClass())) {
                throw new IOException("Bitcoin returned unparsable JSON");
            } else {
                try {
                    responseMessage = (ObjectNode) output;
                } catch (ClassCastException e) {
                    throw new IOException("Bitcoin returned unparsable JSON");
                }
            }

            responseStream.close();
        } catch (JsonProcessingException e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        } catch (IOException e) {
            InputStream errorStream = null;
            IOException e2 = null;

            if (connection.getErrorStream() == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    errorStream = new GZIPInputStream(connection.getErrorStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    errorStream = new InflaterInputStream(connection.getErrorStream());
            } else {
                errorStream = connection.getErrorStream();
            }

            if (errorStream == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            byte[] errorbuf = new byte[8192];

            if (errorStream.read(errorbuf) < 1)
                throw new IOException("Bitcoin returned an error, but with no message");

            String error = new String(errorbuf).trim();

            if (error.startsWith("{")) {
                try {
                    Object output = mapper.readTree(error);

                    if (NullNode.class.equals(output.getClass()))
                        throw new IOException("Bitcoin returned an error message: " + error);
                    else
                        try {
                            responseMessage = (ObjectNode) output;
                        } catch (ClassCastException f) {
                            throw new IOException("Bitcoin returned unparsable JSON");
                        }

                    if (responseMessage.get("error") != null) {
                        if (responseMessage.get("error").get("message") != null
                                && responseMessage.get("error").get("message").asText() != null) {
                            error = responseMessage.get("error").get("message").asText().trim();
                            e2 = new IOException("Bitcoin returned error message: " + error);
                        } else if (responseMessage.get("error").asText() != null) {
                            error = responseMessage.get("error").asText().trim();

                            if (!"null".equals(error) && !"".equals(error))
                                e2 = new IOException("Bitcoin returned an error message: " + error);
                        }
                    }
                } catch (JsonProcessingException f) {
                    e2 = new IOException("Bitcoin returned unparsable JSON");
                }
            } else {
                e2 = new IOException("Bitcoin returned an error message: " + error);
            }

            errorStream.close();

            if (responseStream != null)
                responseStream.close();

            if (e2 == null)
                e2 = new IOException("Bitcoin returned an error, but with no message");

            throw e2;
        }

        if (responseMessage.get("error") != null) {
            if (responseMessage.get("error").get("message") != null
                    && responseMessage.get("error").get("message").asText() != null) {
                String error = responseMessage.get("error").get("message").asText().trim();
                throw new IOException("Bitcoin returned error message: " + error);
            } else if (responseMessage.get("error").asText() != null) {
                String error = responseMessage.get("error").asText().trim();

                if (!"null".equals(error) && !"".equals(error))
                    throw new IOException("Bitcoin returned error message: " + error);
            }
        }

        JsonNode result;

        try {
            result = responseMessage.get("result");
        } catch (Exception e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        }

        if (result == null)
            throw new IOException("Bitcoin did not return a result or an error");

        return result;
    } catch (IOException e) {
        if (connection != null)
            connection.disconnect();

        throw e;
    }
}

From source file:carnero.cgeo.cgBase.java

public void postTweet(cgeoapplication app, cgSettings settings, String status, Double latitude,
        Double longitude) {//from ww w . j  av a 2s  . c om
    if (app == null) {
        return;
    }
    if (settings == null || settings.tokenPublic == null || settings.tokenPublic.length() == 0
            || settings.tokenSecret == null || settings.tokenSecret.length() == 0) {
        return;
    }

    try {
        HashMap<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (latitude != null && longitude != null) {
            parameters.put("lat", String.format("%.6f", latitude));
            parameters.put("long", String.format("%.6f", longitude));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

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

/**
 * @inheritDoc// w  w  w.  j  a v a  2s. c  om
 */
public InputStream openInputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        String con = (String) connection;
        if (con.startsWith("file://")) {
            con = con.substring(7);
        }
        InputStream fc = createFileInputStream(con);
        BufferedInputStream o = new BufferedInputStream(fc, con);
        return o;
    }
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection ht = (HttpURLConnection) connection;
        if (ht.getResponseCode() < 400) {
            return new BufferedInputStream(ht.getInputStream());
        }
        return new BufferedInputStream(ht.getErrorStream());
    } else {
        return new BufferedInputStream(((URLConnection) connection).getInputStream());
    }
}

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./*from  w  w  w .j  av a 2 s  .  co m*/
 * 
 * @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();
        }
    }
}