Example usage for java.net HttpURLConnection setUseCaches

List of usage examples for java.net HttpURLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

private String openRequest(String url, RequestMethod requestMethod, Object paramObject) {
    if (!this.checkNetWork()) {
        // return this.notNetError;
    }/*from  w  w w  . j  a va  2 s .c  o  m*/
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    String response = null;
    PrintWriter out = null;
    try {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "Begin a request--->>>>>>>>>>");
        // }
        // try {
        // url = URLEncoder.encode(url, HttpConstant.ENCODE);
        // } catch (UnsupportedEncodingException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        if (requestMethod == requestMethod.GET && paramObject != null) {
            // try {
            url = url + "?" + this.encodeUrlParam(paramObject);
            // } catch (UnsupportedEncodingException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204
            // 56364.173164,12955.347386
        }
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "url:", url);
        LogUtil.info(this, "requestMethod:", requestMethod);
        LogUtil.info(this, "paramObject:", paramObject);
        // }
        // url = url.replace(" ", "%20");
        conn = (HttpURLConnection) new URL(url).openConnection();
        // System.out
        // .println("this.sessionStr == null" + this.sessionStr == null);
        // System.out.println(this.sessionStr == null);
        if (this.sessionStr != null) {
            conn.setRequestProperty("cookie", sessionStr);
        }
        conn.setConnectTimeout(5 * 1000);
        if (requestMethod == RequestMethod.GET) {
            // conn.setRequestMethod(method);
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            // }
            conn.connect();
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            // http: //
            // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10//
            // Content-Type
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            // conn.setRequestProperty("Content-Type",
            // "application/x-www-form-urlencode");

            // }
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            // conn.connect();
            if (paramObject != null) {
                conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE));
                // out = new PrintWriter(conn.getOutputStream());
                // out.print(paramObject);
                // out.flush();
            }
        }
        inputStream = conn.getInputStream();
        response = read(inputStream);
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "response:", response);
        // }
        if (this.sessionStr == null) {
            Map<String, List<String>> cookies = conn.getHeaderFields();
            // this.cookieHeader = conn.getg
            for (String key : cookies.keySet()) {
                // System.out.println("sdfdsfd:" + key);
                if (key == null) {
                    continue;
                }
                if ("set-cookie".equals(key.toLowerCase())) {
                    List<String> values = cookies.get(key);
                    String sessionStrTemp = "";
                    for (String value : values) {
                        sessionStrTemp += value;
                        sessionStrTemp += ";";
                        // conn.addRequestProperty("set-cookie", string);
                    }
                    // loginSessionStrTemp =
                    // loginSessionStrTemp.substring(0,
                    // loginSessionStrTemp.length() - 1);
                    // System.out.println("loginSessionStrTemp:"
                    // + loginSessionStrTemp);
                    this.sessionStr = sessionStrTemp;
                    this.sessionKey = key;
                    // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp;
                    // BaseHttpManager.sessionStr = loginSessionStrTemp;
                    break;
                }
            }
            // System.out.println("sessionStr:" + sessionStr);
        }
        // System.out.println("openUrl:response:" + response);
    } catch (Exception e) {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "End a request with exception below---XXXXXXXXXX");
        // }
        e.printStackTrace();
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
    // if (AppLibConstant.isUseLog()) {
    LogUtil.info(this, "End a request successfully---VVVVVVVVVV");
    // }
    return response;
}

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

public byte[] openRequestForByteArray(String url, RequestMethod requestMethod, Object paramObject,
        HttpReqestProgressListener httpReqestProgressListener) {
    if (!this.checkNetWork()) {
        // return this.notNetError;
    }// w w w .  j a v a  2  s  .  com
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    // Bitmap bitmap = null;
    byte[] bytes = null;
    try {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "Begin a request--->>>>>>>>>>");
        // }
        // try {
        // url = URLEncoder.encode(url, HttpConstant.ENCODE);
        // } catch (UnsupportedEncodingException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        if (requestMethod == requestMethod.GET && paramObject != null) {
            // try {
            url = url + "?" + this.encodeUrlParam(paramObject);
            // } catch (UnsupportedEncodingException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
            // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204
            // 56364.173164,12955.347386
        }
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "url:", url);
        LogUtil.info(this, "requestMethod:", requestMethod);
        LogUtil.info(this, "paramObject:", paramObject);
        // }
        // url = url.replace(" ", "%20");
        conn = (HttpURLConnection) new URL(url).openConnection();
        // System.out
        // .println("this.sessionStr == null" + this.sessionStr == null);
        // System.out.println(this.sessionStr == null);
        if (this.sessionStr != null) {
            conn.setRequestProperty("cookie", sessionStr);
        }
        conn.setConnectTimeout(5 * 1000);
        if (requestMethod == RequestMethod.GET) {
            // conn.setRequestMethod(method);
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            // }
            conn.connect();
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            // http: //
            // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10//
            // Content-Type
            // if (isMultipart) {
            // conn.setRequestProperty("Content-Type",
            // "multipart/form-data;");
            // } else {
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");

            // }
            // conn.setRequestProperty("Content-Type",
            // "application/x-www-form-urlencode");
            // conn.connect();
            if (paramObject != null) {
                conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE));
            }
        }
        inputStream = conn.getInputStream();
        if (inputStream != null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[128];
            long contentLength = conn.getContentLength();
            int read = -1;
            long downloadCount = 0;
            while ((read = inputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, read);
                downloadCount += read;
                // publishProgress(count * 1.0f / length);
                if (httpReqestProgressListener != null) {
                    httpReqestProgressListener.onRequestProgress(downloadCount * 1f / contentLength);
                }
            }
            bytes = byteArrayOutputStream.toByteArray();
            // File file = new File(params[1]);
            // if (file != null) {
            // FileOutputStream fos = new
            // FileOutputStream(
            // file);
            // fos.write(data);
            // fos.close();
            // }
            // bitmap = BitmapFactory.decodeByteArray(
            // data, 0, data.length);
            // return bit;
            // return bytes;
        }
        // in = new BufferedInputStream(uRLConnection
        // .getInputStream());
        // bitmap = BitmapFactory.decodeStream(inputStream);
        // response = read(inputStream);
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "response:", bytes == null);
        // }
        if (this.sessionStr == null) {
            Map<String, List<String>> cookies = conn.getHeaderFields();
            // this.cookieHeader = conn.getg
            for (String key : cookies.keySet()) {
                // System.out.println("sdfdsfd:" + key);
                if (key == null) {
                    continue;
                }
                if ("set-cookie".equals(key.toLowerCase())) {
                    List<String> values = cookies.get(key);
                    String sessionStrTemp = "";
                    for (String value : values) {
                        sessionStrTemp += value;
                        sessionStrTemp += ";";
                        // conn.addRequestProperty("set-cookie", string);
                    }
                    // loginSessionStrTemp =
                    // loginSessionStrTemp.substring(0,
                    // loginSessionStrTemp.length() - 1);
                    // System.out.println("loginSessionStrTemp:"
                    // + loginSessionStrTemp);
                    this.sessionStr = sessionStrTemp;
                    this.sessionKey = key;
                    // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp;
                    // BaseHttpManager.sessionStr = loginSessionStrTemp;
                    break;
                }
            }
            // System.out.println("sessionStr:" + sessionStr);
        }
        // System.out.println("openUrl:response:" + response);
    } catch (Exception e) {
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info(this, "End a request with exception below---XXXXXXXXXX");
        // }
        if (httpReqestProgressListener != null) {
            httpReqestProgressListener.onRequestFail();
        }
        e.printStackTrace();
        return bytes;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (byteArrayOutputStream != null) {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // if (AppLibConstant.isUseLog()) {
    LogUtil.info(this, "End a request successfully---VVVVVVVVVV");
    // }
    return bytes;
}

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();
    }/* www .  ja va  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.irccloud.android.NetworkConnection.java

public Bitmap fetchImage(URL url, boolean cacheOnly) throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;//w w  w  . jav a  2  s. c  om
    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(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);
    conn.setRequestProperty("User-Agent", useragent);
    if (cacheOnly)
        conn.addRequestProperty("Cache-Control", "only-if-cached");
    Bitmap bitmap = null;

    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) {
        e.printStackTrace();
    }

    try {
        if (conn.getInputStream() != null) {
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        }
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();
    return bitmap;
}

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;/* w ww.j a va 2 s  .  c  o  m*/
    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.yeahka.android.lepos.Device.java

public ResultModel uploadFile(String filePath, String userName) {
    SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String nowDataStr = dataFormat.format(new Date());
    String para = android.os.Build.MODEL + "_" + userName + "_" + nowDataStr + ".data";
    // String para = "LG P970" + "_" + userName + "_" + nowDataStr +
    // ".data";/*from   w w  w  .jav  a2  s  . c  om*/
    para = URLEncoder.encode(para);
    para = para.replaceAll("\\+", "%20");
    String strUrl = UPLOAD_FILE_SERVER_CGI + "?filename=" + para;
    String result = "";
    try {
        InputStream is = new FileInputStream(filePath);
        String strLength = is.available() + "";
        URL url = new URL(strUrl);
        //            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection conn = MyHttps.getHttpURLConnection(url);
        conn.setReadTimeout(10 * 1000);
        conn.setConnectTimeout(10 * 1000);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Coentent_Length", strLength);
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        // StringBuffer sb = new StringBuffer();
        // sb.append("p=");
        // dos.write(sb.toString().getBytes());
        byte[] bytes = new byte[10240];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            // String xmlString = URLEncoder.encode(Base64.encode(bytes, 0,
            // len));
            // byte[] sendData = xmlString.getBytes("UTF-8");
            // dos.write(sendData, 0, sendData.length);
            dos.write(bytes, 0, len);
        }
        is.close();
        dos.flush();
        dos.close();
        /**
         * ??? 200=? ?????
         */
        int res = conn.getResponseCode();
        if (res == 200) {
            InputStream input = conn.getInputStream();
            StringBuffer sb1 = new StringBuffer();
            int ss;
            while ((ss = input.read()) != -1) {
                sb1.append((char) ss);
            }
            result = sb1.toString();
        } else {
            return new ResultModel(Device.TRANSACTION_NET_FAIL);
        }
        return new ResultModel(new String(result));

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (KeyManagementException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}

From source file:com.yeahka.android.lepos.Device.java

/**
 * ?//from   www  .  j  a va2  s  . c om
 *
 * @param actionUrl ?
 * @param file      
 * @return
 * @author "Char"
 * @create_date 2015-8-18
 */
private ResultModel sendPhotoToQuickenLoansWebServer(String actionUrl, File file) {
    try {
        int TIME_OUT = 10 * 1000; // 
        String CHARSET = "utf-8"; // ?
        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); //  ??
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 

        URL url = new URL(actionUrl);
        //            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection conn = MyHttps.getHttpURLConnection(url);
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }
        // ??
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        InputStreamReader isReader = new InputStreamReader(in);
        BufferedReader bufReader = new BufferedReader(isReader);
        String line = null;
        String data = "";

        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            while ((line = bufReader.readLine()) != null) {
                data += line;
            }
        } else {
            return new ResultModel(Device.TRANSACTION_NET_FAIL);
        }
        in.close();
        conn.disconnect();
        return new ResultModel(data);
    } catch (MalformedURLException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL, e);
    } catch (IOException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL, e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL, e);
    } catch (KeyManagementException e) {
        e.printStackTrace();
        return new ResultModel(Device.TRANSACTION_NET_FAIL, e);
    }
}

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

public Object connect(String url, boolean read, boolean write, int timeout) throws IOException {
    URL u = new URL(url);
    CookieHandler.setDefault(null);
    URLConnection con = u.openConnection();
    if (con instanceof HttpURLConnection) {
        HttpURLConnection c = (HttpURLConnection) con;
        c.setUseCaches(false);
        c.setDefaultUseCaches(false);/*  w ww . ja va2 s . c  om*/
        c.setInstanceFollowRedirects(false);
        if (timeout > -1) {
            c.setConnectTimeout(timeout);
        }
        if (read) {
            if (timeout > -1) {
                c.setReadTimeout(timeout);
            } else {
                c.setReadTimeout(10000);
            }
        }
        if (android.os.Build.VERSION.SDK_INT > 13) {
            c.setRequestProperty("Connection", "close");
        }
    }
    con.setDoInput(read);
    con.setDoOutput(write);
    return con;
}