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:org.broad.igv.util.HttpUtils.java

/**
 * The "real" connection method//from  w w  w. j a va 2  s.co  m
 *
 * @param url
 * @param requestProperties
 * @param method
 * @return
 * @throws java.io.IOException
 */
private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method,
        int redirectCount) throws IOException {

    //Encode query string portions
    url = StringUtils.encodeURLQueryString(url);
    if (log.isTraceEnabled()) {
        log.trace(url);
    }

    //Encode base portions. Right now just spaces, most common case
    //TODO This is a hack and doesn't work for all characters which need it
    if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) {
        String newPath = url.toExternalForm().replaceAll(" ", "%20");
        url = new URL(newPath);
    }

    Proxy sysProxy = null;
    boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy;
    //Only check for system proxy if igv proxy settings not found
    if (!igvProxySettingsExist) {
        sysProxy = getSystemProxy(url.toExternalForm());
    }
    boolean useProxy = sysProxy != null || igvProxySettingsExist;

    HttpURLConnection conn;
    if (useProxy) {
        Proxy proxy = sysProxy;
        if (igvProxySettingsExist) {
            if (proxySettings.type == Proxy.Type.DIRECT) {
                proxy = Proxy.NO_PROXY;
            } else {
                proxy = new Proxy(proxySettings.type,
                        new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort));
            }
        }
        conn = (HttpURLConnection) url.openConnection(proxy);

        if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null
                && proxySettings.pw != null) {
            byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes();

            String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes));
            conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
        }
    } else {
        conn = (HttpURLConnection) url.openConnection();
    }

    if (GSUtils.isGenomeSpace(url)) {
        conn.setRequestProperty("Accept", "application/json,text/plain");
    } else {
        conn.setRequestProperty("Accept", "text/plain");
    }

    //------//
    //There seems to be a bug with JWS caches
    //So we avoid caching

    //This default is persistent, really should be available statically but isn't
    conn.setDefaultUseCaches(false);
    conn.setUseCaches(false);
    //------//

    conn.setConnectTimeout(Globals.CONNECT_TIMEOUT);
    conn.setReadTimeout(Globals.READ_TIMEOUT);
    conn.setRequestMethod(method);
    conn.setRequestProperty("Connection", "Keep-Alive");
    if (requestProperties != null) {
        for (Map.Entry<String, String> prop : requestProperties.entrySet()) {
            conn.setRequestProperty(prop.getKey(), prop.getValue());
        }
    }
    conn.setRequestProperty("User-Agent", Globals.applicationString());

    if (method.equals("PUT")) {
        return conn;
    } else {

        int code = conn.getResponseCode();

        if (log.isDebugEnabled()) {
            //logHeaders(conn);
        }

        // Redirects.  These can occur even if followRedirects == true if there is a change in protocol,
        // for example http -> https.
        if (code >= 300 && code < 400) {

            if (redirectCount > MAX_REDIRECTS) {
                throw new IOException("Too many redirects");
            }

            String newLocation = conn.getHeaderField("Location");
            log.debug("Redirecting to " + newLocation);

            return openConnection(new URL(newLocation), requestProperties, method, redirectCount++);
        }

        // TODO -- handle other response codes.
        else if (code >= 400) {

            String message;
            if (code == 404) {
                message = "File not found: " + url.toString();
                throw new FileNotFoundException(message);
            } else if (code == 401) {
                // Looks like this only happens when user hits "Cancel".
                // message = "Not authorized to view this file";
                // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE);
                redirectCount = MAX_REDIRECTS + 1;
                return null;
            } else {
                message = conn.getResponseMessage();
            }
            String details = readErrorStream(conn);
            log.error("URL: " + url.toExternalForm() + ". error stream: " + details);
            log.error("Code: " + code + ". " + message);
            HttpResponseException exc = new HttpResponseException(code);
            throw exc;
        }
    }
    return conn;
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

public boolean downloadMojangLauncher() {
    URL u;//w w  w .  j a  v  a 2 s .c o m
    HttpURLConnection connection;
    Proxy p;
    InputStream is;
    FileOutputStream fos;

    if (new File(config.getInstallDir(), "Minecraft.jar").isFile()) {
        return true;
    }

    log.println("Connecting to Mojang server...");
    if (config.getHttpProxy().isEmpty()) {
        p = Proxy.NO_PROXY;
    } else {
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() == Authenticator.RequestorType.PROXY) {
                    return config.getHttpProxyCredentials();
                } else {
                    return super.getPasswordAuthentication();
                }
            }
        });
        p = new Proxy(Proxy.Type.HTTP, new ProxyAddress(config.getHttpProxy(), 3128).getSockaddr());
    }
    try {
        u = new URL("https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar");
        connection = (HttpURLConnection) u.openConnection(p);
        connection.addRequestProperty("User-agent", "Minecraft Bootloader");
        connection.setUseCaches(false);
        connection.setDefaultUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.connect();
        log.println("Mojang server returned " + connection.getResponseMessage());
        if (connection.getResponseCode() != 200) {
            connection.disconnect();
            return false;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        log.println("Connection to Mojang server failed.");
        return false;
    }

    try {
        is = connection.getInputStream();
        fos = new FileOutputStream(new File(config.getInstallDir(), "Minecraft.jar"));
        log.println("Downloading Minecraft.jar");
        byte[] buffer = new byte[4096];
        for (int n = is.read(buffer); n > 0; n = is.read(buffer)) {
            fos.write(buffer, 0, n);
        }
        fos.close();
        is.close();
        connection.disconnect();
        log.println("Done.");
    } catch (IOException ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "downloadMojangLauncher", ex);
        log.println("Faild to save file.");
        return false;
    }
    return true;
}

From source file:study.tdcc.act.MainCalendar.java

/**
 * XML?????//from   w ww . j  ava2  s. c  om
 * 
 * @param strUrl
 * @param strXml
 * @param strMethod (PUT,DELETE)
 * @return InputStream ???InputStream
 */
public InputStream httpPostXml(String strUrl, String strXml, String strMethod) {
    Log.d("DEBUG", "MainCalendar httpPostXml Start");
    blHttpSucceeded = false;
    try {
        while (strUrl != null) {
            URL urlObj = new URL(strUrl);
            //URL?????
            HttpURLConnection httpURLCObj = (HttpURLConnection) urlObj.openConnection();
            //?POST?
            httpURLCObj.setRequestMethod("POST");
            //GData-Version?
            httpURLCObj.setRequestProperty(GDATA_VERSION_TAG, GDATA_VERSION);
            if (strMethod != null) {
                //POST??????If-Match:*?X-HTTP-Method-Override
                httpURLCObj.setRequestProperty("If-Match", "*");
                httpURLCObj.setRequestProperty("X-HTTP-Method-Override", strMethod);
            }
            //
            httpURLCObj.setDoOutput(true);
            //Content-Type??XML
            httpURLCObj.setRequestProperty("Content-Type", CONTENT_TYPE_AA);
            //
            httpURLCObj.setUseCaches(false);
            //OutputStreamWriter??XML??
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLCObj.getOutputStream(),
                    "UTF-8");
            outputStreamWriter.write(strXml);
            outputStreamWriter.close();
            //HTTP??
            intResponseCode = 0;
            intResponseCode = httpURLCObj.getResponseCode();
            strUrl = null;
            Log.d("DEBUG", "MainCalendar httpPostXml HttpResponseCode : " + intResponseCode);
            if (intResponseCode == HttpURLConnection.HTTP_OK
                    || intResponseCode == HttpURLConnection.HTTP_CREATED) {
                //??OK???CREATED?????
                blHttpSucceeded = true;
                Log.d("DEBUG", "MainCalendar httpPostXml End(1)");
                //?InputStream??
                return httpURLCObj.getInputStream();
            } else if (intResponseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                //??MOVED_TEMP?????????
                //?Location????URL????(?while?
                Map<String, List<String>> mResponseHeaders = httpURLCObj.getHeaderFields();
                if (mResponseHeaders.containsKey("Location")) {
                    strUrl = mResponseHeaders.get("Location").get(0);
                } else if (mResponseHeaders.containsKey("location")) {
                    strUrl = mResponseHeaders.get("location").get(0);
                }
            } else {
                //??OK???CREATED???MOVED_TEMP??
                blHttpSucceeded = false;
                Log.d("DEBUG",
                        "MainCalendar httpPostXml End(2)  ??OK,CREATED,MOVED_TEMP??");
            }
        }
    } catch (Exception e) {
        Log.e("ERROR", "MainCalendar httpPostXml ERROR", e);
    }
    Log.d("DEBUG", "MainCalendar httpPostXml End(3)");
    return null;
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public ArrayList<Element> detailsById(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {/*from  www  . j  a  v a2s . com*/
        URL url;

        if (requestParameters != null) {
            String key;

            query.append("http://api2.yp.com/listings/v1/details?key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "listingid";
            String listingidValue = requestParameters.get(key);
            String listingidDefaultValue = retrieveFromUserDefaultsFor(key);
            if (listingidValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (listingidDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL("http://api2.yp.com/listings/v1/details?key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("listingsDetails");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}

From source file:com.novartis.opensource.yada.test.ServiceTest.java

/**
 * Tests all json and standard queries using HTTP POST
 * //from w  w  w.  j  a v a2  s . c om
 * @param query the query to execute
 * @throws YADAExecutionException when the test fails
 */
@SuppressWarnings("deprecation")
@Test(enabled = true, dataProvider = "QueryTests", groups = { "jsp" })
@QueryFile(list = {})
public void testWithHttpPost(String query) throws YADAExecutionException {
    logQuery(query);
    String method = null;
    HttpURLConnection connection = null;
    String target = "http://" + this.host + this.uri;
    try {
        URL url = new URL(target);
        String urlParameters = "";

        String[] params = query.split(AMP);
        for (int i = 0; i < params.length; i++) {
            String pair = params[i];
            String[] param = pair.split(EQUAL);
            urlParameters += encodeParam(param);
            if (i < params.length - 1)
                urlParameters += AMP;
            if (param[0].equals(YADARequest.PL_METHOD) || param[0].equals(YADARequest.PS_METHOD))
                method = param[1];
        }
        // }
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // auth
        if (Boolean.valueOf(this.auth).booleanValue()) {
            setAuthentication(connection);
        }

        // Send request
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(urlParameters);
            wr.flush();
        }

        // Get Response
        try (InputStream is = connection.getInputStream()) {
            try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
                String line;
                StringBuffer result = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
                try {
                    if (method != null && method.equals(YADARequest.METHOD_UPDATE))
                        Assert.assertTrue(validateInteger(result.toString(), true),
                                "Data invalid for query: " + query);
                    else
                        Assert.assertTrue(validateJSONResult(result.toString()),
                                "Data invalid for query: " + query);
                } catch (Exception e) {
                    Assert.assertTrue(validateThirdPartyJSONResult(result.toString()),
                            "Data invalid for query: " + query);
                }
            }
        }
    } catch (MalformedURLException e) {
        throw new YADAExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new YADAExecutionException(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:JavaTron.AudioTron.java

/**
 * Method to execute a POST Request to the Audiotron - JSC
 * //from  w w  w  .  j a  v  a2s  .  c  o m
 * @param address - The requested page
 * @param args - The POST data
 * @param parser - A Parser Object fit for parsing the response
 *
 * @return null on success, a string on error.  The string describes
 *         the error.
 *
 * @throws IOException
 */
protected String post(String address, Vector args, Parser parser) throws IOException {
    String ret = null;
    URL url;
    HttpURLConnection conn;
    String formData = new String();

    // Build the POST data
    for (int i = 0; i < args.size(); i += 2) {
        if (showPost) {
            System.out.print("POST: " + args.get(i).toString() + " = ");
            System.out.println(args.get(i + 1).toString());
        }
        formData += URLEncoder.encode(args.get(i).toString(), "UTF-8") + "="
                + URLEncoder.encode(args.get(i + 1).toString(), "UTF-8");
        if (i + 2 != args.size())
            formData += "&";
    }

    // Build the connection Headers and POST the data
    try {
        url = new URL("http://" + getServer() + address);
        if (showAddress || showPost) {
            System.out.println("POST: " + address);
            System.out.println("POST: " + formData);
        }
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // Authorization header
        String auth = getUsername() + ":" + getPassword();
        conn.setRequestProperty("Authorization", "Basic " + B64Encode(auth.getBytes()));
        // Debug
        if (showAuth) {
            System.out.println("POST: AUTH: " + auth);
        }
        conn.setRequestProperty("Content Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(formData.getBytes().length));
        conn.setRequestProperty("Content-Language", "en-US");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Send the request to the audiotron
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(formData);
        wr.flush();
        wr.close();

        // Process the Response
        if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) {
            try {
                ret = conn.getResponseMessage();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            if (ret == null) {
                ret = "Unknown Error";
            }
            if (parser != null) {
                parser.begin(ret);
            }
            return ret;
        }

        isr = new InputStreamReader(conn.getInputStream());

        BufferedReader reader = new BufferedReader(isr);
        String s;

        getBuffer = new StringBuffer();

        if (parser != null) {
            parser.begin(null);
        }

        while ((s = reader.readLine()) != null) {
            if (showGet) {
                System.out.println(s);
            }
            getBuffer.append(s);
            getBuffer.append("\n");
            if (parser == null) {
                //  getBuffer.append(s);
            } else {
                if (!parser.parse(s)) {
                    return "Parse Error";
                }
            }
        }

        if (parser == null && showUnparsedOutput) {
            System.out.println(getBuffer);
        }
        if (parser != null) {
            parser.end(false);
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        // if this happens, call the parse method if there is a parser
        // with a null value to indicate an error
        if (parser != null) {
            parser.end(true);
        }
        throw (ioe);
    } finally {
        try {
            isr.close();
        } catch (Exception e) {
            // this is ok
        }
    }

    return ret;
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

public HttpResponse execute(HashMap<String, File> files) throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {//  w ww.  jav a  2s  . c o m
        //            if (parameters != null && !parameters.isEmpty()) {
        //                final StringBuilder buf = new StringBuilder(256);
        //                if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
        //                    buf.append('?');
        //                }
        //
        //                int paramIdx = 0;
        //                for (final Map.Entry<String, String> e : parameters.entrySet()) {
        //                    if (paramIdx != 0) {
        //                        buf.append("&");
        //                    }
        //                    final String name = e.getKey();
        //                    final String value = e.getValue();
        //                    buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
        //                            .append(URLEncoder.encode(value, CONTENT_CHARSET));
        //                    ++paramIdx;
        //                }
        //
        //                if (!contentSet
        //                        && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
        //                    try {
        //                        content = buf.toString().getBytes(CONTENT_CHARSET);
        //                    } catch (UnsupportedEncodingException e) {
        //                        // Unlikely to happen.
        //                        throw new HttpClientException("Encoding error", e);
        //                    }
        //                } else {
        //                    uri += buf;
        //                }
        //            }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        // ?
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CONTENT_CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());

        // ???
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\""
                        + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CONTENT_CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
        }

        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}

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

public byte[] getByteArray(String url, RequestMethod requestMethod, Object paramObject,
        RequestListener fileDownloadListener) {
    if (!this.hasInternet(context)) {
        fileDownloadListener.onFail(RequestFailReason._NET);
        return null;
    }//w  w  w. j a  v a2  s  .c  o m
    HttpURLConnection httpURLConnection = null;
    InputStream inputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        byte[] bytes = null;
        LogUtil.info(this, "Begin a request--->>>>>>>>>>");
        if (requestMethod == requestMethod.GET && paramObject != null) {
            url = url + "?" + this.encodeUrlParam(paramObject);
        }
        LogUtil.info(this, "url:", url);
        LogUtil.info(this, "requestMathod:", requestMethod);
        LogUtil.info(this, "paramObject:", paramObject);
        httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        if (this.sessionStr != null) {
            httpURLConnection.setRequestProperty("cookie", sessionStr);
            // httpURLConnection.setRequestProperty("Accept-Encoding",
            // "identity");
        }
        httpURLConnection.setConnectTimeout(5 * 1000);
        if (requestMethod == RequestMethod.GET) {
            httpURLConnection.setRequestMethod("GET");
            // httpURLConnection.setRequestProperty("Content-Type",
            // "application/x-www-form-urlencode");
            httpURLConnection.setRequestProperty("Accept-Encoding", "identity");
            // System.out.println("BBBBBBBBBBVVVVVVVVVVV");
            httpURLConnection.connect();
        } else {
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
            if (paramObject != null) {
                httpURLConnection.getOutputStream()
                        .write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE));
            }
        }
        double contentLength = httpURLConnection.getContentLength();
        inputStream = httpURLConnection.getInputStream();
        if (inputStream != null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[128];
            // System.out.println(contentLength);
            int read = -1;
            long downloadCount = 0;
            while ((read = inputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, read);
                downloadCount += read;
                fileDownloadListener.onProgress(downloadCount, contentLength);
            }
            bytes = byteArrayOutputStream.toByteArray();
        }
        LogUtil.info(this, "End a request successfully---VVVVVVVVVV");
        LogUtil.info(this, "response:", bytes == null);
        fileDownloadListener.onSuccess(bytes);
        return bytes;
    } catch (Exception e) {
        LogUtil.info(this, "End a request with exception below---XXXXXXXXXX");
        fileDownloadListener.onFail(RequestFailReason.EXCEPTION);
        e.printStackTrace();
        return null;
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        StreamUtil.closeStream(byteArrayOutputStream);
        StreamUtil.closeStream(inputStream);
    }
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public ArrayList<Element> searchByZip(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {/*from  w w w.  j av a 2  s . c o  m*/
        URL url;

        if (requestParameters != null) {
            String key;

            query.append(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "term";
            String termValue = requestParameters.get(key);
            String termDefaultValue = retrieveFromUserDefaultsFor(key);
            if (termValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (termDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }
            key = "searchloc";
            String searchlocValue = requestParameters.get(key);
            String searchlocDefaultValue = retrieveFromUserDefaultsFor(key);
            if (searchlocValue.length() > 0) {
                query.append("&" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (searchlocDefaultValue != null) {
                    query.append("&" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("searchListings");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}