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:com.example.rartonne.appftur.HomeActivity.java

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;/*from w w w  .  ja  va  2  s  . c o m*/
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        //dialog.dismiss();

        Log.e("uploadFile", "Source File not exist");

        runOnUiThread(new Runnable() {
            public void run() {
                //messageText.setText("Source File not exist :"+uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            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("uploaded_file", fileName);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName
                    + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        /*String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                            +" http://www.androidexample.com/media/uploads/"
                            +uploadFileName;*/

                        //messageText.setText(msg);
                        /*Toast.makeText(getApplicationContext(), "File Upload Complete.",
                            Toast.LENGTH_SHORT).show();*/
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            //dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("MalformedURLException Exception : check script url.");
                    /*Toast.makeText(getApplicationContext(), "MalformedURLException",
                        Toast.LENGTH_SHORT).show();*/
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            //dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("Got Exception : see logcat ");
                    /*Toast.makeText(getApplicationContext(), "Got Exception : see logcat ",
                        Toast.LENGTH_SHORT).show();*/
                }
            });
            Log.e("Upload file to server", "Exception : " + e.getMessage(), e);
        }
        // dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;//from  w w  w.  j a v a  2 s  .c om
    }
    URL url = new URL(request.getRequestLine().getUri());

    HttpURLConnection conn = null;

    Proxy proxy = null;
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);

    if (!isRunning)
        return;

    try {
        client.getOutputStream().write(
                ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes());

        if (conn.getResponseCode() == 200 && conn.getInputStream() != null) {
            byte[] buff = new byte[8192];
            int readBytes;
            while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) {
                client.getOutputStream().write(buff, 0, readBytes);
            }
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }

    conn.disconnect();
    stop();
}

From source file:org.ctuning.openme.openme.java

public static JSONObject remote_access(JSONObject i) throws JSONException {
    /*//from  www .  ja  v  a 2  s  . c  om
    Input:  {
      remote_server_url      - remote server URL
      (module_uoa)           - module to run
      (action)               - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (save_to_file)         - if web_action==download,
                                  save output to this file
            
      (out)                  - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to stdout
            
      ...                    - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (error)  - error text, if return > 0
      (stdout) - if out='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";

    x = "";
    if (i.has("out"))
        x = (String) i.get("out");
    if (x != null && x != "")
        con = x;

    String url = "";
    if (i.has("remote_server_url")) {
        url = (String) i.get("remote_server_url");
        i.remove("remote_server_url");
    }
    if (url == null || url == "") {
        r.put("return", new Integer(1));
        r.put("error", "'remote_server_url is not defined");
        return r;
    }

    String save_to_file = "";
    if (i.has("save_to_file")) {
        save_to_file = (String) i.get("save_to_file");
        i.remove("save_to_file");
    }

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = "";
    if (i.has("action")) {
        x = (String) i.get("action");
    }
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "module_uoa=web&action=" + x;

        if (i.has("module_uoa"))
            i.remove("module_uoa");
        if (i.has("out"))
            i.remove("out");
        i.remove("action");
    }

    // Prepare dict to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("dict", i);
    JSONObject rx = convert_array_to_uri(ii);
    if ((Integer) rx.get("return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "ck_json=" + ((String) rx.get("string"));

    // Prepare URL request
    String s = "";
    try {
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (IOException e) {
        if (c != null)
            c.disconnect();
        r.put("return", new Integer(1));
        r.put("error", "Failed sending request to remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Integer(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = "";
        if (i.has("filename")) {
            x = ((String) i.get("filename"));
        }
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Integer(1));
            r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***";
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());
                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json")
            r = new JSONObject(s);
        else
            r.put("stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Retrieves the token from the token pool service.
 *
 * @param owner_id which is operator in Token Pool service
 * @return access token/*  www .j av a2 s  . com*/
 * @throws Exception
 */
private String getPoolAccessToken(String owner_id, String resourceURL) throws Exception {
    StringBuffer result = new StringBuffer();
    HttpURLConnection poolConnection = null;
    URL requestUrl;

    try {

        requestUrl = new URL(resourceURL + URLEncoder.encode(owner_id, "UTF-8"));
        poolConnection = (HttpURLConnection) requestUrl.openConnection();
        poolConnection.setDoOutput(true);
        poolConnection.setInstanceFollowRedirects(false);
        poolConnection.setRequestMethod("GET");
        poolConnection.setRequestProperty("Accept", "application/json");
        poolConnection.setUseCaches(false);

        InputStream input = null;
        if (poolConnection.getResponseCode() == 200) {
            input = poolConnection.getInputStream();
        } else {
            input = poolConnection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }
        br.close();
    } catch (Exception e) {
        log.error("[TokenPoolRequestService ], getPoolAccessToken, " + e.getMessage());
        return null;
    } finally {
        if (poolConnection != null) {
            poolConnection.disconnect();
        }
    }
    return result.toString();
}

From source file:com.sun.identity.security.cert.AMCRLStore.java

private byte[] getCRLByHttpURI(String url) {
    String argString = ""; //default
    StringBuffer params = null;/*from www . j av  a  2 s  .  c  o m*/
    HttpURLConnection con = null;
    byte[] crl = null;

    String uriParamsCRL = storeParam.getURIParams();

    try {

        if (uriParamsCRL != null) {
            params = new StringBuffer();
            StringTokenizer st1 = new StringTokenizer(uriParamsCRL, ",");
            while (st1.hasMoreTokens()) {
                String token = st1.nextToken();
                StringTokenizer st2 = new StringTokenizer(token, "=");
                if (st2.countTokens() == 2) {
                    String param = st2.nextToken();
                    String value = st2.nextToken();
                    params.append(URLEncDec.encode(param) + "=" + URLEncDec.encode(value));
                } else {
                    continue;
                }

                if (st1.hasMoreTokens()) {
                    params.append("&");
                }
            }
        }

        URL uri = new URL(url);
        con = HttpURLConnectionManager.getConnection(uri);

        // Prepare for both input and output
        con.setDoInput(true);

        // Turn off Caching
        con.setUseCaches(false);

        if (params != null) {
            byte[] paramsBytes = params.toString().trim().getBytes("UTF-8");
            if (paramsBytes.length > 0) {
                con.setDoOutput(true);
                con.setRequestProperty("Content-Length", Integer.toString(paramsBytes.length));

                // Write the arguments as post data
                BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
                out.write(paramsBytes, 0, paramsBytes.length);
                out.flush();
                out.close();
            }
        }
        // Input ...
        InputStream in = con.getInputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int len;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            bos.write(buf, 0, len);
        }
        crl = bos.toByteArray();

        if (debug.messageEnabled()) {
            debug.message("AMCRLStore.getCRLByHttpURI: crl.length = " + crl.length);
        }
    } catch (Exception e) {
        debug.error("getCRLByHttpURI : Error in getting CRL", e);
    }

    return crl;
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {
    AQUtility.debug("multipart", url);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;/*from ww  w.jav a  2s .  co  m*/
    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(NET_TIMEOUT * 4);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);
    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }
    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, conn);
    }
    dos = new DataOutputStream(conn.getOutputStream());
    Object o = null;
    if (progress != null) {
        o = progress.get();
    }
    Progress p = null;
    if (o != null) {
        p = new Progress(o);
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        writeObject(dos, entry.getKey(), entry.getValue(), p);
    }
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();
    conn.connect();
    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();
    byte[] data = null;
    String encoding = conn.getContentEncoding();
    String error = null;
    if ((code < 200) || (code >= 300)) {
        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");
        AQUtility.debug("error", error);
    } else {
        data = toData(encoding, conn.getInputStream());
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

public int uploadFile(String sourceFileUri) {
    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php";
    String fileName = sourceFileUri;
    Log.d("file upload url", upLoadServerUri);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;// ww w.j  av  a 2s.  c om
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.d("uploadFile", "Source File Does not exist");
        return 0;
    }
    int serverResponseCode = 0;
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        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("uploaded_file", fileName);

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

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-"
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        //close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();
        Log.d("Contact file ", "uploaded");
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. //from   w  ww. ja  v  a  2s  .  c  o  m
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

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

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *///from w  ww  .j  ava  2s.  c om
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                PSFileUploadResult result = new PSFileUploadResult();
                PSFileProgressResult progress = new PSFileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);
                conn.setRequestProperty("Content-Type", mimeType);

                // Set the cookies on the response
                String cookie = CookieManager.getInstance().getCookie(target);
                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentOutputStream = sendStream;
                    }
                    //We don't want to change encoding, we just want this to write for all Unicode.

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                context.currentOutputStream = null;
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param httpParam//  w ww  .  j a va2s .c o m
 * @return
 */
public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) {
    String url = httpParam.getUrl();
    Map<String, Object> parameters = httpParam.getParameters();
    String sMethod = httpParam.getMethod();
    String charSet = httpParam.getCharSet();
    boolean sslVerify = httpParam.isSslVerify();
    int maxResultSize = httpParam.getMaxResultSize();
    Map<String, Object> headers = httpParam.getHeaders();
    int readTimeout = httpParam.getReadTimeout();
    int connectTimeout = httpParam.getConnectTimeout();
    boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess();
    boolean hostnameVerify = httpParam.isHostnameVerify();
    TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore();
    ClientKeyStore clientKeyStore = httpParam.getClientKeyStore();

    if (url == null || url.trim().length() == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }
    if (maxResultSize <= 0) {
        throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize);
    }
    Charset.forName(charSet);
    HttpURLConnection urlConn = null;
    URL destURL = null;

    String baseUrl = url.trim();
    if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) {
        baseUrl = HTTP_PREFIX + baseUrl;
    }

    String method = null;
    if (sMethod != null) {
        method = sMethod.toUpperCase();
    }
    if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) {
        throw new IllegalArgumentException("invalid http method : " + method);
    }

    int index = baseUrl.indexOf("?");
    if (index > 0) {
        baseUrl = urlEncode(baseUrl, charSet);
    } else if (index == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }

    String queryString = mapToQueryString(parameters, charSet);
    String targetUrl = "";
    if (method.equals(HTTP_METHOD_POST)) {
        targetUrl = baseUrl;
    } else {
        if (index > 0) {
            targetUrl = baseUrl + "&" + queryString;
        } else {
            targetUrl = baseUrl + "?" + queryString;
        }
    }
    try {
        destURL = new URL(targetUrl);
        urlConn = (HttpURLConnection) destURL.openConnection();

        setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore);

        boolean hasContentType = false;
        boolean hasUserAgent = false;
        for (String key : headers.keySet()) {
            if ("Content-Type".equalsIgnoreCase(key)) {
                hasContentType = true;
            }
            if ("user-agent".equalsIgnoreCase(key)) {
                hasUserAgent = true;
            }
        }
        if (!hasContentType) {
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet);
        }
        if (!hasUserAgent) {
            headers.put("user-agent", "PlatSystem");
        }

        if (headers != null && !headers.isEmpty()) {
            for (Entry<String, Object> entry : headers.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                List<String> values = makeStringList(value);
                for (String v : values) {
                    urlConn.addRequestProperty(key, v);
                }
            }
        }
        urlConn.setDoOutput(true);
        urlConn.setDoInput(true);
        urlConn.setAllowUserInteraction(false);
        urlConn.setUseCaches(false);
        urlConn.setRequestMethod(method);
        urlConn.setConnectTimeout(connectTimeout);
        urlConn.setReadTimeout(readTimeout);

        if (method.equals(HTTP_METHOD_POST)) {
            String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString;
            if (postData != null && postData.trim().length() > 0) {
                OutputStream os = urlConn.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, charSet);
                osw.write(postData);
                osw.flush();
                osw.close();
            }
        }

        int responseCode = urlConn.getResponseCode();
        Map<String, List<String>> responseHeaders = urlConn.getHeaderFields();
        String contentType = urlConn.getContentType();

        SimpleHttpResult result = new SimpleHttpResult(responseCode);
        result.setHeaders(responseHeaders);
        result.setContentType(contentType);

        if (responseCode != 200 && ignoreContentIfUnsuccess) {
            return result;
        }

        InputStream is = urlConn.getInputStream();
        byte[] temp = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readBytes = is.read(temp);
        while (readBytes > 0) {
            baos.write(temp, 0, readBytes);
            readBytes = is.read(temp);
        }
        String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet);
        baos.close();
        result.setContent(resultString);
        return result;
    } catch (Exception e) {
        logger.warn("connection error : " + e.getMessage());
        return new SimpleHttpResult(e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
}