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:BihuHttpUtil.java

/**
 * ??HTTPJSON?/*from   w ww.  ja va 2  s  .co  m*/
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * send a HTTP POST request/*w w w  . j a va  2s .c  o  m*/
 * @param param
 * @param input_url
 * @return
 */
public static String POST(String param, String input_url) {
    try {
        URL url = new URL(input_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/xml");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        PrintWriter xmlOut = new PrintWriter(con.getOutputStream());
        xmlOut.write(param);
        xmlOut.flush();
        BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = "";
        String line;
        while ((line = response.readLine()) != null) {
            result += "\n" + line;
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.technicpack.launchercore.util.DownloadUtils.java

public static String getETag(String address) {
    String md5 = "";

    try {//from   w w w. j a v a 2 s.  c  om
        URL url = new URL(address);
        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");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);

        String eTag = conn.getHeaderField("ETag");
        if (eTag != null) {
            eTag = eTag.replaceAll("^\"|\"$", "");
            if (eTag.length() == 32) {
                md5 = eTag;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return md5;
}

From source file:net.technicpack.launchercore.util.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  .  j  av a  2 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");
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:net.nym.library.http.UploadImagesRequest.java

/**
 * ???// ww  w. j av  a 2  s. com
 *
 * @param url
 *            Service net address
 * @param params
 *            text content
 * @param files
 *            pictures
 * @return String result of Service response
 * @throws java.io.IOException
 */
public static String postFile(String url, Map<String, Object> params, Map<String, File> files)
        throws IOException {
    String result = "";
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";

    StringBuilder sb = new StringBuilder("?");
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        //                sb.append(PREFIX);
        //                sb.append(BOUNDARY);
        //                sb.append(LINEND);
        //                sb.append("Content-Disposition: form-data; name=\""
        //                        + entry.getKey() + "\"" + LINEND);
        //                sb.append("Content-Type: text/plain; charset=" + CHARSET
        //                        + LINEND);
        //                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        //                sb.append(LINEND);
        //                sb.append(entry.getValue());
        //                sb.append(LINEND);
        //                String key = entry.getKey();
        //                sb.append("&");
        //                sb.append(key).append("=").append(params.get(key));
        //                Log.i("%s=%s",key,params.get(key).toString());
        sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString()))
                .append("&");
    }
    sb.deleteCharAt(sb.length() - 1);
    URL uri = new URL(url + sb.toString());
    HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
    conn.setConnectTimeout(50000);
    conn.setDoInput(true);// ?
    conn.setDoOutput(true);// ?
    conn.setUseCaches(false); // ??
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    // ?
    //            StringBuilder sb = new StringBuilder();
    //            for (Map.Entry<String, Object> entry : params.entrySet()) {
    ////                sb.append(PREFIX);
    ////                sb.append(BOUNDARY);
    ////                sb.append(LINEND);
    ////                sb.append("Content-Disposition: form-data; name=\""
    ////                        + entry.getKey() + "\"" + LINEND);
    ////                sb.append("Content-Type: text/plain; charset=" + CHARSET
    ////                        + LINEND);
    ////                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
    ////                sb.append(LINEND);
    ////                sb.append(entry.getValue());
    ////                sb.append(LINEND);
    //                String key = entry.getKey();
    //                sb.append("&");
    //                sb.append(key).append("=").append(params.get(key));
    //                Log.i("%s=%s",key,params.get(key).toString());
    //            }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    //            outStream.write(sb.toString().getBytes());
    // ?
    if (files != null) {
        for (Map.Entry<String, File> file : files.entrySet()) {
            StringBuilder sbFile = new StringBuilder();
            sbFile.append(PREFIX);
            sbFile.append(BOUNDARY);
            sbFile.append(LINEND);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                    + file.getValue().getName() + "\"" + LINEND);
            sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
            sbFile.append(LINEND);
            Log.i(sbFile.toString());
            outStream.write(sbFile.toString().getBytes());

            InputStream is = new FileInputStream(file.getValue());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            outStream.write(LINEND.getBytes());
        }
        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
    }

    outStream.flush();
    // ??
    int res = conn.getResponseCode();
    InputStream in = conn.getInputStream();
    StringBuilder sbResult = new StringBuilder();
    if (res == 200) {
        int ch;
        while ((ch = in.read()) != -1) {
            sbResult.append((char) ch);
        }
    }
    result = sbResult.toString();
    outStream.close();
    conn.disconnect();
    return result;
}

From source file:org.apdplat.superword.tools.ProxyIp.java

/**
 * ??IP?????IP/*  w  w  w  .ja  v  a 2  s  .co m*/
 * @param host
 * @param port
 * @return
 */
public static boolean verify(String host, int port) {
    try {
        String url = "http://apdplat.org";
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder html = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            html.append(line);
        }
        LOGGER.info("HTML" + html);
        if (html.toString().contains("APDPlat???")) {
            LOGGER.info("?IP??" + host + ":" + port);
            return true;
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    LOGGER.info("?IP?" + host + ":" + port);
    return false;
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?/*from  ww w  . jav a  2  s .  com*/
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url/*from w  w  w . j  a  v  a 2  s. c o m*/
 *
 * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param file the output file. If it is a folder, it tries to get the file name from the header.
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). 
 *           Note: This method will add the question mark (?) to the request - 
 *           DO NOT add it yourself
 * @param user
 * @param password
 * @return the file written. 
 * @throws Exception 
 */
public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user,
        String password) throws Exception {
    if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
    }
    HttpURLConnection conn = makeNewConnection(urlStr);
    conn.setRequestMethod("GET");
    // conn.setDoOutput(true);
    conn.setDoInput(true);
    // conn.setChunkedStreamingMode(0);
    conn.setUseCaches(false);

    if (user != null && password != null) {
        conn.setRequestProperty("Authorization", getB64Auth(user, password));
    }
    conn.connect();

    if (file.isDirectory()) {
        // try to get the header
        String headerField = conn.getHeaderField("Content-Disposition");
        String fileName = null;
        if (headerField != null) {
            String[] split = headerField.split(";");
            for (String string : split) {
                String pattern = "filename=";
                if (string.toLowerCase().startsWith(pattern)) {
                    fileName = string.replaceFirst(pattern, "");
                    break;
                }
            }
        }
        if (fileName == null) {
            // give a name
            fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date());
        }
        file = new File(file, fileName);
    }

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[(int) maxBufferSize];
        int bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        }
        out.flush();

    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
    return file;
}

From source file:org.apache.mycat.advisor.common.net.http.HttpService.java

/**
 * ? header?//from  ww  w. j a v a 2  s . c  om
 *
 * @param requestUrl
 * @param requestMethod
 * @param WithTokenHeader
 * @param token
 * @return
 */
public static String doHttpRequest(String requestUrl, String requestMethod, Boolean WithTokenHeader,
        String token) {
    String result = null;
    InetAddress ipaddr;
    int responseCode = -1;
    try {
        ipaddr = InetAddress.getLocalHost();
        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);
        if (WithTokenHeader) {
            if (token == null) {
                throw new IllegalStateException("Oauth2 token is not set!");
            }
            httpUrlConn.setRequestProperty("Authorization", "OAuth2 " + token);
            httpUrlConn.setRequestProperty("API-RemoteIP", ipaddr.getHostAddress());
        }
        // ?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:itdelatrisu.opsu.Utils.java

/**
 * Returns a the contents of a URL as a string.
 * @param url the remote URL//from   w  ww .  ja  v a  2s .co  m
 * @return the contents as a string, or null if any error occurred
 * @author Roland Illig (http://stackoverflow.com/a/4308662)
 * @throws IOException if an I/O exception occurs
 */
public static String readDataFromUrl(URL url) throws IOException {
    // open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(Download.CONNECTION_TIMEOUT);
    conn.setReadTimeout(Download.READ_TIMEOUT);
    conn.setUseCaches(false);
    try {
        conn.connect();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }

    if (Thread.interrupted())
        return null;

    // read contents
    try (InputStream in = conn.getInputStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = rd.read()) != -1)
            sb.append((char) c);
        return sb.toString();
    } catch (SocketTimeoutException e) {
        Log.warn("Connection to server timed out.", e);
        throw e;
    }
}