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:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;// w w w .  j a va2 s.  c  o m
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(15 * 1000);
        con.setReadTimeout(15 * 1000);
        con.connect();
        try (OutputStream out = con.getOutputStream()) {
            out.write(post.toString().getBytes(Charset.forName("UTF-8")));
        }
        con.getResponseCode();
        InputStream instr;
        instr = con.getErrorStream();
        if (instr == null) {
            instr = con.getInputStream();
        }
        byte[] data = new byte[1024];
        int length;
        try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) {
            try (InputStream in = new BufferedInputStream(instr)) {
                while ((length = in.read(data)) >= 0) {
                    bytes.write(data, 0, length);
                }
            }
            byte[] rawBytes = bytes.toByteArray();
            if (rawBytes.length != 0) {
                obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8")));
            } else {
                obj = new JSONObject();
            }
            if (!ignoreErrors && obj.has("error")) {
                String error = obj.getString("error");
                String errorMessage = obj.getString("errorMessage");
                String cause = obj.optString("cause", null);
                if ("ForbiddenOperationException".equals(error)) {
                    if ("UserMigratedException".equals(cause)) {
                        throw new UserMigratedException(errorMessage);
                    }
                    throw new ForbiddenOperationException(errorMessage);
                }
                throw new AuthorizationException(
                        error + (cause != null ? "." + cause : "") + ": " + errorMessage);
            }
            return obj;
        }
    } catch (JSONException ex) {
        throw new InvalidResponseException(ex, obj);
    }
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Opens a POST connection./* w  ww.  j a  va2s.  c om*/
 *
 * @param url The URL to connect to.
 *
 * @return A POST connection to this URL.
 * @throws IOException If an exception occurred while contacting the server.
 */
static private HttpURLConnection getPOSTConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    return connection;
}

From source file:com.lostad.app.base.util.RequestUtil.java

/** 
 * HTTP??????,??? /*from  ww  w . j a  va2 s  . c o  m*/
 * @param actionUrl  
 * @param params ? key???,value? 
 * @param files 
 * @throws Exception 
 */
public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token)
        throws Exception {
    try {
        String BOUNDARY = "---------7d4a6d158c9"; //?  
        String MULTIPART_FORM_DATA = "multipart/form-data";

        URL url = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);//?  
        conn.setDoOutput(true);//?  
        conn.setUseCaches(false);//?Cache  
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        conn.setRequestProperty("token", token);
        //????
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {//?  
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                sb.append(entry.getValue());
                sb.append("\r\n");
            }
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());//????  

        //??  
        for (FormFile file : files) {
            StringBuilder split = new StringBuilder();
            split.append("--");
            split.append(BOUNDARY);
            split.append("\r\n");
            split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\""
                    + file.getFilname() + "\"\r\n");
            split.append("Content-Type: " + file.getContentType() + "\r\n\r\n");
            outStream.write(split.toString().getBytes());
            outStream.write(file.getData(), 0, file.getData().length);
            outStream.write("\r\n".getBytes());
        }
        byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//??           
        outStream.write(end_data);
        outStream.flush();
        int cah = conn.getResponseCode();
        if (cah != 200)
            throw new RuntimeException("url");
        InputStream is = conn.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        outStream.close();
        conn.disconnect();
        return b.toString();
    } catch (Exception e) {

        throw e;
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Http/*w ww .j a va 2 s . c  o m*/
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param outputJson    ?
 * @return 
 */
public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {/*from   w w  w  .ja  v  a  2 s.  c o m*/
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream postConnection(Context context, URL url, String method, String urlParameters)
        throws IOException {
    if (!url.getProtocol().startsWith("http")) {
        return url.openStream();
    }/*w  w  w  . java2 s .c  o m*/

    URLConnection c = url.openConnection();

    HttpURLConnection connection = (HttpURLConnection) c;

    connection.setRequestMethod(method.toUpperCase());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

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

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

    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(urlParameters.getBytes("UTF-8"));
        output.flush();
    } finally {
        IOUtils.close(output);
    }
    return connection.getInputStream();
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?url/*from w  ww .  j  ava  2  s .c o  m*/
 *
 * @param inputStream ?
 * @param fileName    ??
 * @param fileType    
 * @param contentType 
 * @param identity    
 * @return 
 */
public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName,
        String fileType, String contentType, String identity) {
    String lineEnd = System.getProperty("line.separator");
    String twoHyphens = "--";
    String boundary = "*****";
    String result = null;
    try {
        //?
        URL submit = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) submit.openConnection();
        //
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        //?
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", DEFAULT_CHARSET);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //??
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName
                + ";Content-Type=\"" + contentType + lineEnd);
        dos.writeBytes(lineEnd);

        byte[] buffer = new byte[8192]; // 8k
        int count = 0;
        while ((count = inputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        inputStream.close(); //?
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();

        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET);
        BufferedReader br = new BufferedReader(isr);
        result = br.readLine();
        dos.close();
        is.close();
    } catch (IOException e) {
        logger.error("", e);
    }
    return result;
}

From source file:Main.java

public static String executePost(String url, String parameters) throws IOException {

    URL request = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) request.openConnection();
    connection.setDoOutput(true);/*  ww  w .  ja v  a  2s  .c o m*/
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("User-Agent", "StripeConnectAndroid");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
    connection.setUseCaches(false);

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

    String response = streamToString(connection.getInputStream());
    connection.disconnect();
    return response;

}

From source file:net.technicpack.utilslib.Utils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 *
 * @param url The URL to set up and receive content from
 * @return A valid HttpURLConnection//from ww  w .ja  va2  s.com
 * @throws IOException The openConnection() method throws an IOException and the calling method is responsible for handling it.
 */
public static HttpURLConnection openHttpConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    System.setProperty("http.agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
    conn.setUseCaches(false);
    return conn;
}

From source file:org.alfresco.repo.web.scripts.tenant.TenantAdminSystemTest.java

private static String callInOutWeb(String urlString, String method, String ticket, String data,
        String contentType, String soapAction) throws MalformedURLException, URISyntaxException, IOException {
    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);//from  w w  w .  j a  v  a2  s  . c o  m

    conn.setRequestProperty("Content-type", contentType);

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

    if (soapAction != null) {
        conn.setRequestProperty("SOAPAction", soapAction);
    }

    if (ticket != null) {
        // add Base64 encoded authorization header
        // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication
        conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes()));
    }

    String result = null;
    BufferedReader br = null;
    DataOutputStream wr = null;
    OutputStream os = null;
    InputStream is = null;

    try {
        os = conn.getOutputStream();
        wr = new DataOutputStream(os);
        wr.write(data.getBytes());
        wr.flush();
    } finally {
        if (wr != null) {
            wr.close();
        }
        ;
        if (os != null) {
            os.close();
        }
        ;
    }

    try {
        is = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));

        String line = null;
        StringBuffer sb = new StringBuffer();
        while (((line = br.readLine()) != null)) {
            sb.append(line);
        }

        result = sb.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        ;
        if (is != null) {
            is.close();
        }
        ;
    }

    return result;
}