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:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);//from  w w w.ja  va2s .  c  om

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}

From source file:com.example.scandevice.MainActivity.java

public static String excutePost(String targetURL, String urlParameters) {
    URL url;//from   w w w.j  a  v  a  2s. c o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

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

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

    } catch (Exception e) {
        e.printStackTrace();
        return "Don't post data";

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return "Data Sent";
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from w w  w  . j  ava 2  s.  c o  m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends a string via POST to a given url.
 *
 * @param context      the context to use.
 * @param urlStr       the url to which to send to.
 * @param string       the string to send as post body.
 * @param user         the user or <code>null</code>.
 * @param password     the password or <code>null</code>.
 * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message.
 * @return the response.//from  w w  w.  j  a v  a 2s.  c o m
 * @throws Exception if something goes wrong.
 */
public static String sendPost(Context context, String urlStr, String string, String user, String password,
        boolean readResponse) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        // Make server believe we are form data...
        wr = new BufferedOutputStream(conn.getOutputStream());
        byte[] bytes = string.getBytes();
        wr.write(bytes);
        wr.flush();

        int responseCode = conn.getResponseCode();
        if (readResponse) {
            StringBuilder returnMessageBuilder = new StringBuilder();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    returnMessageBuilder.append(line + "\n");
                }
                br.close();
            }

            return returnMessageBuilder.toString();
        } else {
            return getMessageForCode(context, responseCode,
                    context.getResources().getString(R.string.post_completed_properly));
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.screenslicer.common.CommonUtil.java

public static void postQuickly(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {/*from w ww. j ava2 s.  co m*/
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//from  w  w w.j  av a 2 s. c o  m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.screenslicer.common.CommonUtil.java

public static String post(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {/*from w  w  w . ja v a 2 s  .c  o  m*/
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(0);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        if (conn.getResponseCode() == 205) {
            return NOT_BUSY;
        }
        if (conn.getResponseCode() == 423) {
            return BUSY;
        }
        return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
    return "";
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * //w w  w .j  a  v a2 s.c  o  m
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

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

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }//ww w.  j ava2 s.  c o m

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:com.linkbubble.util.Util.java

public static String downloadJSONAsString(String url, int timeout) {
    try {//from  w ww .  j a v  a  2  s  . com
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-length", "0");
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.connect();
        int status = connection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();
        }

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return null;
}