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.wisdom.openid.connect.service.internal.DefaultIssuer.java

@Override
public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException {

    StringBuilder sb = new StringBuilder();
    sb.append("grant_type=authorization_code");
    sb.append(format("&code=%s", code));
    sb.append(format("&client_id=%s", clientId));
    sb.append(format("&client_secret=%s", clientSecret));
    sb.append(format("&redirect_uri=%s", redirectUrl));

    String parameters = sb.toString();

    URL tokenEndpoint = new URL(config.getTokenEndpoint());
    HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection();
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //connection.addRequestProperty("Authorization", format("Basic %s", credentials()));
    connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length));

    connection.setUseCaches(false);
    connection.setDoInput(true);/*from  w  w w.  j  av  a 2 s. c o  m*/
    connection.setDoOutput(true);

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

    //Get Response
    return buildTokenResponse(connection.getInputStream());
}

From source file:com.helpmobile.rest.RestAccess.java

public String doJsonRequest(String request, String data, String method)
        throws MalformedURLException, IOException {
    URL path = new URL(ADDRESS + request);
    HttpURLConnection conn = (HttpURLConnection) path.openConnection();
    conn.setRequestMethod(method);//  w  ww. ja v a2s.  c o m
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Content-Length ", Integer.toString(data.length()));
    conn.setRequestProperty("AppKey", KEY);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    if (data.length() != 0) {
        conn.setDoOutput(true);
        OutputStream output = conn.getOutputStream();
        output.write(data.getBytes("UTF-8"));
        output.flush();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    conn.disconnect();
    //print result
    return (String) response.toString();
}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report./* w w  w. ja va 2 s .c  o m*/
 *
 * @param context         the application context
 * @param withDevicesLogs true to include the device logs
 * @param withCrashLogs   true to include the crash logs
 */
private static void sendBugReport(final Context context, final boolean withDevicesLogs,
        final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) {
    new AsyncTask<Void, Integer, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report");

            if (bugReportFile.exists()) {
                bugReportFile.delete();
            }

            String serverError = null;
            FileWriter fileWriter = null;

            try {
                fileWriter = new FileWriter(bugReportFile);
                JsonWriter jsonWriter = new JsonWriter(fileWriter);
                jsonWriter.beginObject();

                // android bug report
                jsonWriter.name("user_agent").value("Android");

                // logs list
                jsonWriter.name("logs");
                jsonWriter.beginArray();

                // the logs are optional
                if (withDevicesLogs) {
                    List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>());
                    for (File f : files) {
                        if (!mIsCancelled) {
                            jsonWriter.beginObject();
                            jsonWriter.name("lines").value(convertStreamToString(f));
                            jsonWriter.endObject();
                            jsonWriter.flush();
                        }
                    }
                }

                if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) {
                    jsonWriter.beginObject();
                    jsonWriter.name("lines").value(getLogCatError());
                    jsonWriter.endObject();
                    jsonWriter.flush();
                }

                jsonWriter.endArray();

                jsonWriter.name("text").value(bugDescription);

                String version = "";

                if (null != Matrix.getInstance(context).getDefaultSession()) {
                    version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n";
                }

                version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " "
                        + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n";
                version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n";
                version += "SDK version:  " + Matrix.getInstance(context).getDefaultSession().getVersion(true)
                        + "\n";
                version += "Olm version:  "
                        + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true)
                        + "\n";

                jsonWriter.name("version").value(version);

                jsonWriter.endObject();
                jsonWriter.close();

            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage());
                serverError = e.getLocalizedMessage();
            } catch (OutOfMemoryError oom) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage());
                serverError = oom.getMessage();

                if (TextUtils.isEmpty(serverError)) {
                    serverError = "Out of memory";
                }
            }

            try {
                if (null != fileWriter) {
                    fileWriter.close();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage());
            }

            if (TextUtils.isEmpty(serverError) && !mIsCancelled) {

                // the screenshot is defined here
                // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg");
                InputStream inputStream = null;
                HttpURLConnection conn = null;
                try {
                    inputStream = new FileInputStream(bugReportFile);
                    final int dataLen = inputStream.available();

                    // should never happen
                    if (0 == dataLen) {
                        return "No data";
                    }

                    URL url = new URL(context.getResources().getString(R.string.bug_report_url));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Content-Length", Integer.toString(dataLen));
                    // avoid caching data before really sending them.
                    conn.setFixedLengthStreamingMode(inputStream.available());

                    conn.connect();

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    byte[] buffer = new byte[8192];

                    // read file and write it into form...
                    int bytesRead;
                    int totalWritten = 0;

                    while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
                        dos.write(buffer, 0, bytesRead);
                        totalWritten += bytesRead;
                        publishProgress(totalWritten * 100 / dataLen);
                    }

                    dos.flush();
                    dos.close();

                    int mResponseCode;

                    try {
                        // Read the SERVER RESPONSE
                        mResponseCode = conn.getResponseCode();
                    } catch (EOFException eofEx) {
                        mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
                    }

                    // if the upload failed, try to retrieve the reason
                    if (mResponseCode != HttpURLConnection.HTTP_OK) {
                        serverError = null;
                        InputStream is = conn.getErrorStream();

                        if (null != is) {
                            int ch;
                            StringBuilder b = new StringBuilder();
                            while ((ch = is.read()) != -1) {
                                b.append((char) ch);
                            }
                            serverError = b.toString();
                            is.close();

                            // check if the error message
                            try {
                                JSONObject responseJSON = new JSONObject(serverError);
                                serverError = responseJSON.getString("error");
                            } catch (JSONException e) {
                                Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage());
                            }

                            // should never happen
                            if (null == serverError) {
                                serverError = "Failed with error " + mResponseCode;
                            }

                            is.close();
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG,
                            "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage());
                    serverError = e.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Failed to upload";
                    }
                } catch (OutOfMemoryError oom) {
                    Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage());
                    serverError = oom.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Out ouf memory";
                    }

                } finally {
                    try {
                        if (null != conn) {
                            conn.disconnect();
                        }
                    } catch (Exception e2) {
                        Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage());
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage());
                    }
                }
            }
            return serverError;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            if (null != listener) {
                try {
                    listener.onProgress((null == progress) ? 0 : progress[0]);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(String reason) {
            if (null != listener) {
                try {
                    if (mIsCancelled) {
                        listener.onUploadCancelled();
                    } else if (null == reason) {
                        listener.onUploadSucceed();
                    } else {
                        listener.onUploadFailed(reason);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage());
                }
            }
        }
    }.execute();
}

From source file:foam.blob.RestBlobService.java

@Override
public Blob put_(X x, Blob blob) {
    if (blob instanceof IdentifiedBlob) {
        return blob;
    }/*  w  w w .  j a  v a  2 s  . co  m*/

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

    try {
        URL url = new URL(address_);
        connection = (HttpURLConnection) url.openConnection();

        //configure HttpURLConnection
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        //set request method
        connection.setRequestMethod("PUT");

        //configure http header
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/octet-stream");

        // get connection ouput stream
        os = connection.getOutputStream();

        //output blob into connection
        blob.read(os, 0, blob.getSize());

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Upload failed");
        }

        is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        CharBuffer cb = CharBuffer.allocate(65535);
        reader.read(cb);
        cb.rewind();

        return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        IOUtils.close(connection);
    }
}

From source file:com.reddit.util.ApiUtil.java

/**
 * Experimental right now.  I messed around with this but never really used it for anything.
 * /*from w ww. ja v  a  2s.c o  m*/
 * @param url should be new URL("https://ssl.reddit.com/api/login/myusername");
 * @param user
 * @param pw
 * @throws IOException
 * @throws JSONException
 */
public void login(URL url, String user, String pw) throws IOException, JSONException {

    String data = "api_type=json&user=" + user + "&passwd=" + pw;
    HttpURLConnection httpUrlConn = null;
    httpUrlConn = (HttpURLConnection) url.openConnection();
    httpUrlConn.setRequestMethod("POST");
    httpUrlConn.setDoOutput(true);
    httpUrlConn.setUseCaches(false);
    httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpUrlConn.setRequestProperty("Content-Length", String.valueOf(data.length()));

    DataOutputStream dataOutputStream = new DataOutputStream(httpUrlConn.getOutputStream());
    dataOutputStream.writeBytes(data);
    dataOutputStream.flush();
    dataOutputStream.close();
    InputStream is = httpUrlConn.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuffer response = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    for (Entry<String, List<String>> r : httpUrlConn.getHeaderFields().entrySet()) {
        System.out.println(r.getKey() + ": " + r.getValue());
    }
    bufferedReader.close();
    System.out.println("Response: " + response.toString());
    this.setModHash(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("modhash"));
    this.setCookie(new JSONObject(response.toString()).getJSONObject("json").getJSONObject("data")
            .getString("cookie"));

}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean login(String username, String password) throws IOException {
    preLogin();//from   w  w w.  ja va2s  . c om
    URL url = new URL(LOGIN_HOST + LOGIN_SUFFIX);
    HttpURLConnection httpURLConnection_a = (HttpURLConnection) url.openConnection();
    httpURLConnection_a.setRequestMethod("POST");
    httpURLConnection_a.setUseCaches(false);
    httpURLConnection_a.setInstanceFollowRedirects(false);
    httpURLConnection_a.setDoOutput(true);

    String OUTPUT_DATA = "username=";
    OUTPUT_DATA += username;
    OUTPUT_DATA += "&password=";
    OUTPUT_DATA += password;
    OUTPUT_DATA += "&submit=";
    OUTPUT_DATA += "&lt=" + LOGIN_PARAM_lt;
    OUTPUT_DATA += "&execution=" + LOGIN_PARAM_execution;
    OUTPUT_DATA += "&_eventId=" + LOGIN_PARAM__eventId;
    OUTPUT_DATA += "&rmShown=" + LOGIN_PARAM_rmShown;

    httpURLConnection_a.setRequestProperty("Cookie",
            "route=" + ROUTE
                    + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; JSESSIONID="
                    + LOGIN_JSESSIONID + "; BIGipServeridsnew.xidian.edu.cn=" + BIGIP_SERVER_IDS_NEW + ";");

    httpURLConnection_a.connect();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection_a.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(OUTPUT_DATA);
    outputStreamWriter.flush();
    outputStreamWriter.close();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection_a.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("a");
    if (elements.size() == 0)
        return false;
    String SYS_LOCATION = elements.get(0).attr("href");

    URL sys_location = new URL(SYS_LOCATION);
    HttpURLConnection httpUrlConnection_b = (HttpURLConnection) sys_location.openConnection();
    httpUrlConnection_b.setInstanceFollowRedirects(false);
    httpUrlConnection_b.connect();
    List<String> cookies_to_set = httpUrlConnection_b.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(11, e.indexOf(";"));
    httpURLConnection_a.disconnect();
    httpUrlConnection_b.disconnect();
    return checkIsLogin(username);
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 *
 * @param url/*w w w .  j a  va2s.c  o m*/
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

From source file:org.aksw.gerbil.bat.annotator.AgdistisAnnotator.java

public HashSet<Annotation> getAnnotations(String textWithMentions) throws IOException, ParseException {
    URL agdistisUrl = new URL("http://" + host + ":" + port + "/AGDISTIS");
    String parameters = "type=agdistis&text=" + URLEncoder.encode(textWithMentions, "UTF-8");
    HttpURLConnection slConnection = (HttpURLConnection) agdistisUrl.openConnection();
    slConnection.setDoOutput(true);//w ww.  j a v a2s. c  o m
    slConnection.setDoInput(true);
    slConnection.setRequestMethod("POST");
    slConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    slConnection.setRequestProperty("charset", "utf-8");
    slConnection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
    slConnection.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    InputStream in = slConnection.getInputStream();
    HashSet<Annotation> annotations = parseJsonStream(in);
    return annotations;
}

From source file:es.tor.push.android.Sender.java

protected HttpURLConnection post(String url, String contentType, String body) throws IOException {
    if (url == null || body == null) {
        throw new IllegalArgumentException("arguments cannot be null");
    }//from www. j  a  va 2  s  .  co m
    if (!url.startsWith("https://")) {
        logger.warning("URL does not use https: " + url);
    }
    logger.fine("Sending POST to " + url);
    logger.finest("POST body: " + body);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = getConnection(url);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", contentType);
    conn.setRequestProperty("Authorization", "key=" + key);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();
    return conn;
}