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.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Gets the cookie which is needed to extract the content of aip pages.
 * (changed code from ScrapingContext.getContentAsString) 
 * @param urlConn Connection to api page (from url.openConnection())
 * @return The value of the cookie./*from w w  w .j a  v  a2  s  .  c om*/
 * @throws IOException
 */
private String getCookie() throws IOException {
    HttpURLConnection urlConn = (HttpURLConnection) new URL("http://www.blackwell-synergy.com/help")
            .openConnection();
    String cookie = null;

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // extract cookie from header
    Map map = urlConn.getHeaderFields();
    cookie = urlConn.getHeaderField("Set-Cookie");
    if (cookie != null && cookie.indexOf(";") >= 0)
        cookie = cookie.substring(0, cookie.indexOf(";"));

    urlConn.disconnect();
    return cookie;
}

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL//  w w w  .  j  av a2s .  c  o  m
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:com.threeti.proxy.RequestFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String path = request.getServletPath();
    String pathInfo = path.substring(path.lastIndexOf("/"));

    if (pathInfo == null) {
        response.getWriter().write("error");
    } else {/*  w  w  w. j  a v  a 2 s. c  o m*/
        if (path.contains("/proxy")) {
            pathInfo = path.substring(path.lastIndexOf("/proxy") + 6);
            if ("POST".equals(request.getMethod())) { // POST
                String urlString = this.baseURL + pathInfo;
                logger.info(urlString);
                String s = this.getParams(req).substring(0, this.getParams(req).length() - 1);
                byte[] data = s.getBytes("utf-8");
                HttpURLConnection conn = null;
                DataOutputStream outStream = null;
                URL httpUrl = new URL(urlString);
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "utf-8");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                outStream = new DataOutputStream(conn.getOutputStream());
                outStream.write(data);
                outStream.flush();
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else if ("DELETE".equals(request.getMethod())) {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                HttpURLConnection conn = null;
                URL url = new URL(urlString);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("DELETE");
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                URL url = new URL(urlString);
                InputStream input = url.openStream();
                IOUtils.copy(input, response.getOutputStream());
            }
        } else {
            chain.doFilter(req, res);
        }
    }
}

From source file:com.vimc.ahttp.HurlWorker.java

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

    connection.setConnectTimeout(request.connectTimeout);
    connection.setReadTimeout(request.soTimeout);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // connection.setRequestProperty("Connection", "close");

    if ("https".equals(url.getProtocol())) {
        if (mSslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
        } else {
            setDefaultSSLSocketFactory();
        }
    }

    return connection;
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * /*from www .  ja v a 2s.  c o m*/
 * @param url
 * @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:com.attask.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }//from  w w w  .j av a  2 s.  co  m

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);
    conn.connect();

    return conn;
}

From source file:com.anyonavinfo.commonuserregister.MainActivity.java

/**
 * Post?/*from  w  w w . jav a2  s .  co  m*/
 */
public static String doPost(String urlStr, File file) {
    URL url = null;
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestProperty("encoding", "utf-8");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream IS = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = IS.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            IS.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                Log.d("Sjj--->", len + "");
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        // 
        if (e instanceof SocketTimeoutException) {
            return "SocketTimeoutException";
        } else if (e instanceof UnknownHostException) {
            return "UnknownHostException";
        }
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            if (baos != null)
                baos.close();
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException e) {
        }
    }

    return null;
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

protected void configConnection(HttpURLConnection connection) throws IOException {
    connection.setConnectTimeout(mConnectTimeout);
    connection.setReadTimeout(mReadTimeout);
    connection.setUseCaches(false);
    connection.setDoInput(true);/*from   w ww  .  j  ava 2  s.  c  o m*/
    connection.setRequestProperty("Charset", Charset.defaultCharset().name());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent", mUserAgent);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Cookie", CookieHelper.parse(mRequestParams.getCookies()));

    switch (mType) {
    case TYPE_TEXT: {
        connection.setRequestMethod(mMethod.name());
        if (mMethod == Method.POST) {
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", CONTENT_TYPE_TEXT);
            String paramsString;
            if (!TextUtils.isEmpty(mRequestParams.getString())) {
                paramsString = mRequestParams.getString();
            } else {
                paramsString = parseMapToUrlParamsString(mRequestParams.getArrayMap());
            }
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(paramsString.getBytes());
            outputStream.flush();
            outputStream.close();
        }
        break;
    }
    case TYPE_BITMAP: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }
        outputStream.write(builder.toString().getBytes());

        outputStream.writeBytes(PREFIX + BOUNDARY + LINE_END);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "bitmap" + "\";filename=\""
                + "bitmap.jpg" + "\"" + LINE_END);
        outputStream.writeBytes(LINE_END);
        outputStream.write(bitmapToBytes(mBitmap));
        outputStream.writeBytes(LINE_END);
        outputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);
        outputStream.flush();
        outputStream.close();
        break;
    }
    case TYPE_FILE: {
        connection.setRequestMethod(Method.POST.name());
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_FILE);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : mRequestParams.getArrayMap().entrySet()) {
            builder.append(PREFIX).append(BOUNDARY).append(LINE_END);
            builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"")
                    .append(LINE_END);
            builder.append("Content-Type: text/plain; charset=\"utf-8\"").append(LINE_END);
            builder.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            builder.append(LINE_END);
            builder.append(entry.getValue());
            builder.append(LINE_END);
        }

        for (ArrayMap.Entry<String, File> entry : mFileMap.entrySet()) {
            String text = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"; filename=\"" + entry.getValue().getName() + "\"" + LINE_END
                    + "Content-Type:" + "application/octet-stream" + LINE_END
                    + "Content-Transfer-Encoding: binary" + LINE_END + LINE_END;
            outputStream.writeBytes(builder.append(text).toString());

            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(entry.getValue()));
            int length;
            byte[] bytes = new byte[1024 * 1024];
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
        }

        String endTag = LINE_END + PREFIX + BOUNDARY + PREFIX + LINE_END;
        outputStream.writeBytes(endTag);
        outputStream.flush();
        outputStream.close();
        break;
    }
    }
}

From source file:net.phalapi.sdk.PhalApiClient.java

protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
    String result = null;/*from ww w . jav a2  s.  c  om*/
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;

    url = new URL(requestUrl);
    connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST"); // ?
    connection.setUseCaches(false);
    connection.setConnectTimeout(timeoutMs);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    //POST?
    String postContent = "";
    Iterator<Entry<String, String>> iter = params.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
        postContent += "&" + entry.getKey() + "=" + entry.getValue();
    }
    out.writeBytes(postContent);
    out.flush();
    out.close();

    Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);

    in = new InputStreamReader(connection.getInputStream());
    BufferedReader bufferedReader = new BufferedReader(in);
    StringBuffer strBuffer = new StringBuffer();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        strBuffer.append(line);
    }
    result = strBuffer.toString();

    Log.d("[PhalApiClient apiResult]", result);

    if (connection != null) {
        connection.disconnect();
    }

    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

/******************************************************************************************
 * Uploads the note to the server/*from ww  w  .ja v a  2s .c  o m*/
 ******************************************************************************************
 * @param currentNoteId Unique note ID to be uploaded
 * @return True if uploaded, false if not
 ******************************************************************************************/
boolean uploadOneNote(long currentNoteId) {
    boolean result = false;
    final String postUrl = "http://FountainCityCycling.org/post/";

    try {

        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        /*
        Change protocol to 2 for Note, and change the point where you zip up the body.  (Dont zip up trip body)
        Since notes don't work either, this may not solve it.
         */

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

        JSONObject note = getNoteJSON(currentNoteId);
        deviceId = getDeviceId();

        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"note\"\r\n\r\n" + note.toString() + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
                + String.valueOf(kSaveNoteProtocolVersion) + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"device\"\r\n\r\n" + deviceId + "\r\n");

        if (imageDataNull == false) {
            dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                    + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n"
                    + "Content-Type: image/jpeg\r\n\r\n");
            dos.write(imageData);
            dos.writeBytes("\r\n");
        }

        dos.writeBytes("--cycle*******notedata*******columbus--\r\n");

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

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        // JSONObject responseData = new JSONObject(serverResponseMessage);
        Log.v("KENNY", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        responseMessage = serverResponseMessage;
        responseCode = serverResponseCode;

        // 200 - 202 means successfully went to server and uploaded
        if (serverResponseCode == 200 || serverResponseCode == 201 || serverResponseCode == 202) {
            mDb.open();
            mDb.updateNoteStatus(currentNoteId, NoteData.STATUS_SENT);
            mDb.close();
            result = true;
        }
    } catch (IllegalStateException e) {
        Log.d("KENNY", "Note Catch: Illegal State Exception: " + e);
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        Log.d("KENNY", "Note Catch: IOException: " + e);
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        Log.d("KENNY", "Note Catch: JSONException: " + e);
        e.printStackTrace();
        return false;
    }
    return result;
}