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.apache.oltu.oauth2.client.OAuthClientTest.java

public static void main(String[] args) throws OAuthSystemException, IOException {
    String callback = "http://localhost:8080/";
    String clientId = "131804060198305";
    String secret = "3acb294b071c9aec86d60ae3daf32a93";

    String host = "http://smoke-track.herokuapp.com";
    host = "http://localhost:3000";
    String authUri = host + "/oauth/authorize";
    String tokenUri = host + "/oauth/token";
    String appUri = host + "/habits";

    callback = "http://localhost:8080";

    clientId = "728ad798943fff1afd90e79765e9534ef52a5b166cfd25f055d1c8ff6f3ae7fd";
    secret = "3728e0449052b616e2465c04d3cbd792f2d37e70ca64075708bfe8b53c28d529";

    clientId = "e42ae40e269d9a546316f93e42edf52a18934c6a68de035f8b615343c4b81eb0";
    secret = "3b1a720c311321c29852dc4735517f6ece0c991d4be677539cb430c7ee4d1097";

    try {/*  ww w . j a v  a  2s.  c  om*/
        OAuthClientRequest request = OAuthClientRequest.authorizationLocation(authUri).setClientId(clientId)
                .setRedirectURI(callback).setResponseType("code").buildQueryMessage();

        //in web application you make redirection to uri:
        System.out.println("Visit: " + request.getLocationUri() + "\nand grant permission");

        System.out.print("Now enter the OAuth code you have received in redirect uri ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String code = br.readLine();

        request = OAuthClientRequest.tokenLocation(tokenUri).setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId(clientId).setClientSecret(secret).setRedirectURI(callback).setCode(code)
                .buildBodyMessage();

        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

        OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request,
                OAuthJSONAccessTokenResponse.class);

        System.out.println("Access Token: " + oAuthResponse.getAccessToken() + ", Expires in: "
                + oAuthResponse.getExpiresIn());

        URL appURL = new URL(appUri);
        HttpURLConnection con = (HttpURLConnection) appURL.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate");
        con.setRequestProperty("Authorization", "Bearer " + oAuthResponse.getAccessToken());

        JSONObject body = new JSONObject();
        body.put("color", "green");
        body.put("name", "Java Test");
        body.put("description", "Test Habit");

        byte[] bodyBytes = body.toString().getBytes();

        con.setRequestProperty("Content-Length", Integer.toString(bodyBytes.length));

        con.setInstanceFollowRedirects(false);
        con.setUseCaches(false);
        con.setDoInput(true);
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(bodyBytes);
        wr.flush();
        wr.close();

        //InputStream is = con.getInputStream();
        int status = con.getResponseCode();
        System.out.println("Status: " + status);
    } catch (OAuthProblemException e) {
        System.out.println("OAuth error: " + e.getError());
        System.out.println("OAuth error description: " + e.getDescription());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static HttpURLConnection openUrlConnection(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setUseCaches(false);
    conn.setChunkedStreamingMode(0);/*from w ww  . j  a  va2 s  . co  m*/
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.connect();
    return conn;
}

From source file:Main.java

private static HttpURLConnection defineHttpsURLConnection(HttpURLConnection connection, JSONObject jsonObject) {
    try {// w ww .  j  av a2  s. c  o m
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /* Add headers to the request */
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(jsonObject.toString().getBytes(Charset.forName("UTF-8")));
        wr.flush();
        wr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connection;
}

From source file:Main.java

private static HttpURLConnection _openPostConnection(String purl) throws IOException {
    URL url = new URL(purl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);/*from  w  w  w .  j  a va2s  .co m*/
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("User-Agent", "Android Client Agent");

    return connection;
}

From source file:Main.java

public static String getToken(String email, String password) throws IOException {
    // Create the post data
    // Requires a field with the email and the password
    StringBuilder builder = new StringBuilder();
    builder.append("Email=").append(email);
    builder.append("&Passwd=").append(password);
    builder.append("&accountType=GOOGLE");
    builder.append("&source=markson.visuals.sitapp");
    builder.append("&service=ac2dm");

    // Setup the Http Post
    byte[] data = builder.toString().getBytes();
    URL url = new URL("https://www.google.com/accounts/ClientLogin");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);/*from ww  w  .j  a va2  s.  c om*/
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", Integer.toString(data.length));

    // Issue the HTTP POST request
    OutputStream output = con.getOutputStream();
    output.write(data);
    output.close();

    // Read the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line = null;
    String auth_key = null;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("Auth=")) {
            auth_key = line.substring(5);
        }
    }

    // Finally get the authentication token
    // To something useful with it
    return auth_key;
}

From source file:Main.java

public static int sendMessage(String auth_token, String registrationId, String message) throws IOException {

    StringBuilder postDataBuilder = new StringBuilder();
    postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId);
    postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0");
    postDataBuilder.append("&").append("data.payload").append("=")
            .append(URLEncoder.encode("Lars war hier", UTF8));

    byte[] postData = postDataBuilder.toString().getBytes(UTF8);

    // Hit the dm URL.

    URL url = new URL("https://android.clients.google.com/c2dm/send");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*  www  . j  a va2s .  c  o  m*/
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token);

    OutputStream out = conn.getOutputStream();
    out.write(postData);
    out.close();

    int responseCode = conn.getResponseCode();
    return responseCode;
}

From source file:me.malladi.dashcricket.Util.java

/**
 * Fetch the current live scores.//from  w  w w  .ja  v a2 s . c om
 * 
 * @return An array of the current live scores.
 */
public static LiveScore[] getLiveScores() {
    try {
        URL url = new URL(LIVE_SCORES_URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        StringBuilder json = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }

        JSONArray jsonArray = new JSONArray(json.toString());
        LiveScore[] liveScores = new LiveScore[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); ++i) {
            JSONObject liveScoreJson = (JSONObject) jsonArray.opt(i);
            liveScores[i] = new LiveScore(liveScoreJson);
        }

        return liveScores;
    } catch (Exception e) {
        Log.e(TAG, "exception while fetching live scores", e);
    }
    return null;
}

From source file:Main.java

static public String download_json(String url_addr) {
    StringBuilder result = new StringBuilder();
    try {//from   w w w. j a va 2  s . c o m
        URL url = new URL(url_addr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn != null) {
            conn.setConnectTimeout(10000);
            conn.setUseCaches(false);
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                for (;;) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    result.append(line + '\n');
                }
                br.close();
            } else {
                conn.disconnect();
                return null;
            }
            conn.disconnect();
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return null;
    }
    return result.toString();
}

From source file:Main.java

public static void post(String actionUrl, String file) {
    try {//  w w  w. j  av  a2  s .com
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.technicpack.launchercore.auth.AuthenticationService.java

private static String postJson(String url, String data) throws IOException {
    byte[] rawData = data.getBytes("UTF-8");
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);//from   www  . j a  va 2  s  .  com
    connection.setDoInput(true);
    connection.setConnectTimeout(15000);
    connection.setReadTimeout(15000);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.setRequestProperty("Content-Length", rawData.length + "");
    connection.setRequestProperty("Content-Language", "en-US");

    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.write(rawData);
    writer.flush();
    writer.close();

    InputStream stream = null;
    String returnable = null;
    try {
        stream = connection.getInputStream();
        returnable = IOUtils.toString(stream);
    } catch (IOException e) {
        stream = connection.getErrorStream();

        if (stream == null) {
            throw e;
        }
    } finally {
        try {
            if (stream != null)
                stream.close();
        } catch (IOException e) {
        }
    }

    return returnable;
}