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.melniqw.instagramsdk.Network.java

private static String sendDummyRequest(String url, String body, Request request) throws IOException {
    HttpURLConnection connection = null;
    try {/*from www .  ja v  a2s. co  m*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        //            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        if (request == Request.GET) {
            connection.setDoOutput(false);
            connection.setRequestMethod("GET");
        } else if (request == Request.POST) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        }
        if (REQUEST_ENABLE_COMPRESSION)
            connection.setRequestProperty("Accept-Encoding", "gzip");
        if (request == Request.POST)
            connection.getOutputStream().write(body.getBytes("utf-8"));
        int code = connection.getResponseCode();
        System.out.println(TAG + " responseCode = " + code);
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1)
            throw new WrongResponseCodeException("Network error");
        // ?    200
        //on error can also read error stream from connection.
        InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
        String encoding = connection.getHeaderField("Content-Encoding");
        if (encoding != null && encoding.equalsIgnoreCase("gzip"))
            inputStream = new GZIPInputStream(inputStream);
        String response = Utils.convertStreamToString(inputStream);
        System.out.println(TAG + " response = " + response);
        return response;
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;//w ww . ja  v a2 s. co  m

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}

From source file:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }//  w  w w. j ava  2  s .  c  om
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

public static HttpURLConnection createUrlConnection(final URL url) throws IOException {
    Validate.notNull(url);//w  ww .ja va  2s.c  om
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(15000);
    connection.setUseCaches(false);
    return connection;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Create a new Http connection for an URI.
 *///from  w  ww .  j  a  v  a2s.c  o m
public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies)
        throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Setup connection to " + uri);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(60000);
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("User-Agent", getUserAgent(context));
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);

    // Close the connection when the request is done, or the application may
    // freeze due to a bug in some Android versions.
    conn.setRequestProperty("Connection", "close");

    if (conn instanceof HttpsURLConnection) {
        setupSecureConnection(context, (HttpsURLConnection) conn);
    }

    if (cookies != null && !cookies.isEmpty()) {
        final StringBuilder buf = new StringBuilder(256);
        for (final String cookie : cookies) {
            if (buf.length() != 0) {
                buf.append("; ");
            }
            buf.append(cookie);
        }
        conn.addRequestProperty("Cookie", buf.toString());
    }

    return conn;
}

From source file:network.module.transaction.HttpUtils.java

public static String httpConnectionForString(String address, TestData testData, String httpMethod)
        throws IOException {
    if (address == null) {
        throw new IllegalArgumentException("address must not be null.");
    }//w  ww.  j a v a 2 s  .co  m
    try {
        URL url = new URL(address);
        Log.i(TAG, "address = " + url.toString());
        Log.i(TAG, "httpMethod = " + httpMethod);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setRequestMethod(httpMethod);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        OutputStream outputStream = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEncodedQuery(testData));
        writer.flush();
        writer.close();
        outputStream.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = conn.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] byteBuffer = new byte[1024];
            byte[] byteData = null;
            int nLength = 0;
            while ((nLength = inputStream.read(byteBuffer, 0, byteBuffer.length)) != -1) {
                byteArrayOutputStream.write(byteBuffer, 0, nLength);
            }
            byteData = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();

            return new String(byteData);
        } else {
            Log.e(TAG, "responseCode = " + responseCode);
        }
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, address);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, address);
    } catch (SocketException e) {
        handleHttpConnectionException(e, address);
    } catch (Exception e) {
        handleHttpConnectionException(e, address);
    }
    return null;
}

From source file:network.module.transaction.HttpUtils.java

public static JSONObject httpConnectionForJSONObject(String address, TestData testData, String httpMethod)
        throws IOException {
    if (address == null) {
        throw new IllegalArgumentException("address must not be null.");
    }//  w ww.  j a va  2 s.  co m
    try {
        URL url = new URL(address);
        Log.i(TAG, "address = " + url.toString());
        Log.i(TAG, "httpMethod = " + httpMethod);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIME_OUT);
        conn.setReadTimeout(TIME_OUT);
        conn.setRequestMethod(httpMethod);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        OutputStream outputStream = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEncodedQuery(testData));
        writer.flush();
        writer.close();
        outputStream.flush();
        outputStream.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = conn.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] byteBuffer = new byte[1024];
            byte[] byteData = null;
            int nLength = 0;
            while ((nLength = inputStream.read(byteBuffer, 0, byteBuffer.length)) != -1) {
                byteArrayOutputStream.write(byteBuffer, 0, nLength);
            }
            byteData = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(new String(byteData));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject;
        } else {
            Log.e(TAG, "responseCode = " + responseCode);
        }
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, address);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, address);
    } catch (SocketException e) {
        handleHttpConnectionException(e, address);
    } catch (Exception e) {
        handleHttpConnectionException(e, address);
    }
    return null;
}

From source file:bg.phpgcm2.RegistrationIntentService.java

private static void post(String endpoint, Map<String, String> params) throws IOException {

    URL url;/*from   w w  w  .  ja v  a 2  s.  c om*/
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {//from   ww w  . ja v a2  s. co m
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Creates a connection object for requesting a single profile name
 * /*from w  ww . j ava  2s.c  om*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param name The name to request
 * @return The {@link HttpURLConnection} to Mojang's server
 * @throws IOException If there is a problem opening the stream, a malformed
 *                     URL, or if there is a ProtocolException
 */
private static HttpURLConnection createSingleProfileConnection(String name) throws IOException {
    URL url = new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s?at=0", name));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    return connection;
}