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:gov.nasa.arc.geocam.geocam.HttpPost.java

public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) {
    try {/*from  w w  w . j  ava  2  s. c o m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipartFiles(out, vars, files);

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        return "Encoding exception: " + e;
    } catch (IOException e) {
        return "IOException: " + e;
    } catch (IllegalStateException e) {
        return "IllegalState: " + e;
    }
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server./*from   w  ww .j  ava2s  . c om*/
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    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(LOG_TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // 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.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;//from  w  w  w  .  j  av a  2  s  .  co m

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

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

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makeGetConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from w w  w .ja v a  2s . co  m*/
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

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

    return conn;
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context)
        throws IOException {
    URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip
            + "&format=xml");
    //URL url = new URL("http://ipinfodb.com/ip_query.php");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);// www.java2  s  .c o  m
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Get user position by IP stream is = ", theString);

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("stream", theString);
    return paramOut;
}

From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java

private static HttpURLConnection makePostConnection(URL url, byte[] bytes) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from w w  w . j  a  va 2  s.c o  m
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Add in API key
    String authKey = new String(Base64.encodeBase64((key + ":").getBytes()));
    conn.setRequestProperty("Authorization", "Basic " + authKey);

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

    return conn;
}

From source file:net.andylizi.colormotd.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;//from   w w w  . java  2  s.c o m
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}

From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java

/**
 * Makes a HTTP POST request for authentication.
 *
 * @param emailUserName the name of the user
 * @param password the password of the user
 * @param loginTokenOfCaptcha CAPTCHA token (Optional)
 * @param loginCaptchaAnswer answer of CAPTCHA token (Optional)
 * @return http response as a String/* www.j  av  a2 s  .c om*/
 * @throws IOException
 */
// TODO: Refactor requestAuthentication() utilizing HttpPost.
private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha,
        String loginCaptchaAnswer) throws IOException {

    // Prepare connection.
    URL url = new URL(URL_GOOGLE_LOGIN);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
    logger.fine("url: " + url);

    // Form the POST params.
    StringBuilder params = new StringBuilder();
    params.append("Email=").append(emailUserName).append("&Passwd=").append(password)
            .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE");
    if (loginTokenOfCaptcha != null) {
        params.append("&logintoken=").append(loginTokenOfCaptcha);
    }
    if (loginCaptchaAnswer != null) {
        params.append("&logincaptcha=").append(loginCaptchaAnswer);
    }

    // Send POST via output stream.
    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve response.
    // TODO: Should the caller of this method need to know the responseCode?
    int responseCode = urlConnection.getResponseCode();
    logger.fine("responseCode: " + responseCode);
    InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream()
            : urlConnection.getErrorStream();

    logger.fine("inputStream: " + inputStream);
    try {
        String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING);
        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:com.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);//w  w w .j a  v  a  2  s .co m
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:net.andylizi.colormotd.anim.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;//w ww.  java  2 s.c  o m
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", Main.getInstance().getDescription().getFullName());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}