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.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? ? //from  www  .java 2s  .  c  o m
 * @param access_token ??
 * @param msgType image?voice?videothumb
 * @param localFile 
 * @return
 */
@Deprecated
public static String uploadMedia(String access_token, String msgType, String localFile) {
    String media_id = null;
    String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type="
            + msgType;
    String local_url = localFile;
    try {
        File file = new File(local_url);
        if (!file.exists() || !file.isFile()) {
            log.error("==" + local_url);
            return null;
        }
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST"); // Post????get?
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post??
        // ?
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        // 
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
        // con.setRequestProperty("Content-Type",
        // "multipart/mixed; boundary=" + BOUNDARY);
        // con.setRequestProperty("content-type", "text/html");
        // ?

        // 
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////?
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // ?
        OutputStream out = new DataOutputStream(con.getOutputStream());
        out.write(head);

        // 
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ??
        out.write(foot);
        out.flush();
        out.close();
        /**
         * ????,?????
         */
        // con.getResponseCode();
        try {
            // BufferedReader???URL?
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                // System.out.println(line);
                buffer.append(line);
            }
            String respStr = buffer.toString();
            log.debug("==respStr==" + respStr);
            try {
                JSONObject dataJson = JSONObject.parseObject(respStr);

                media_id = dataJson.getString("media_id");
            } catch (Exception e) {
                log.error("==respStr==" + respStr, e);
                try {
                    JSONObject dataJson = JSONObject.parseObject(respStr);
                    return dataJson.getString("errcode");
                } catch (Exception e1) {
                }
            }
        } catch (Exception e) {
            log.error("??POST?" + e);
        }
    } catch (Exception e) {
        log.error("?!=" + local_url);
        log.error("?!", e);
    } finally {
    }
    return media_id;
}

From source file:org.bibsonomy.util.WebUtils.java

/**
 * Reads from a URL and writes the content into a string.
 * /*  w w w.  java2s .  com*/
 * @param inputURL the URL of the content.
 * @param cookie a cookie which should be included in the header of the request send to the server
 * @return String which holds the page content.
 * @throws IOException 
 * 
 * @Deprecated
 */
public static String getContentAsString(final URL inputURL, final String cookie) throws IOException {
    try {
        final HttpURLConnection urlConn = (HttpURLConnection) inputURL.openConnection();
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(false);
        urlConn.setUseCaches(false);

        /*
         * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some 
         * pages require it to download content.
         */
        urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE);
        if (cookie != null) {
            urlConn.setRequestProperty(COOKIE_HEADER_NAME, cookie);
        }
        urlConn.connect();

        /*
         * extract character encoding from header
         */
        final String charSet = getCharset(urlConn);

        /*
         * FIXME: check content type header to ensure that we only read textual 
         * content (and not a PDF, radio stream or DVD image ...)
         */

        /*
         * write content into string buffer
         */
        final StringBuilder out = inputStreamToStringBuilder(urlConn.getInputStream(), charSet);

        urlConn.disconnect();

        return out.toString();
    } catch (final ConnectException cex) {
        log.debug("Could not get content for URL " + inputURL.toString() + " : " + cex.getMessage());
        throw new IOException(cex);
    } catch (final IOException ioe) {
        log.debug("Could not get content for URL " + inputURL.toString() + " : " + ioe.getMessage());
        throw ioe;
    }
}

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Fetches the list of friend data updates from the server
 * /*  w ww  .  ja  v  a  2  s .c  o m*/
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken,
        long serverSyncState/*Date lastUpdated*/, String type_contact)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<User> friendList = new ArrayList<User>();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_OPERATION, "sync"));
    params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName));
    if (serverSyncState == 0)
        params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... 
    else
        params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState)));
    params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... 
    Log.d(TAG, "fetchFriendUpdates");
    //   params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;"));
    //        if (lastUpdated != null) {
    //            final SimpleDateFormat formatter =
    //                new SimpleDateFormat("yyyy/MM/dd HH:mm");
    //            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    //            params.add(new BasicNameValuePair(PARAM_UPDATED, formatter
    //                .format(lastUpdated)));
    //        }

    // HTTP GET REQUEST
    URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8"));
    HttpURLConnection con;
    con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Content-length", "0");
    con.setRequestProperty("accept", "application/json");

    con.setUseCaches(false);
    con.setAllowUserInteraction(false);
    int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception
    con.setConnectTimeout(timeout);
    con.setReadTimeout(timeout);
    con.connect();
    int status = con.getResponseCode();

    LastFetchOperationStatus = true;
    if (status == HttpURLConnection.HTTP_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        String response = sb.toString();
        Log.i(TAG, "--response--");
        // <Hack> to bypass vtiger 5.4 webservice bug:
        int idx = response.indexOf("{\"success");
        response = response.substring(idx);
        Log.i(TAG, response);
        // </Hack>
        Log.i(TAG, "--response end--");
        JSONObject result = new JSONObject(response);

        String success = result.getString("success");
        Log.i(TAG, "success is" + success);
        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            final JSONObject data = new JSONObject(result.getString("result"));
            final JSONArray friends = new JSONArray(data.getString("updated"));
            // == VTiger updated contacts ==
            for (int i = 0; i < friends.length(); i++) {
                friendList.add(User.valueOf(friends.getJSONObject(i)));
            }
            // == Vtiger contacts deleted ===
            String deleted_contacts = data.getString("deleted");
            Log.d(TAG, deleted_contacts);
            Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("[")));
            List<String> items = Arrays.asList(
                    deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]"))
                            .split("\\s*,\\s*"));
            for (int ii = 0; ii < items.size(); ii++) {
                Log.d(TAG, items.get(ii));
                if (items.get(ii).startsWith("\"4x")) // this is a contact
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}");
                    friendList.add(User.valueOf(item));
                }
                if (items.get(ii).startsWith("\"3x")) // this is an account
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}");
                    friendList.add(User.valueOf(item));
                }
                if (items.get(ii).startsWith("\"2x")) // this is a lead
                {
                    //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}");
                    JSONObject item = new JSONObject(
                            "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}");
                    friendList.add(User.valueOf(item));
                }
            }
        } else {
            LastFetchOperationStatus = false;
            // FIXME: else false...
            // possible error code :
            //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}}
            //               throw new AuthenticationException();
        }
    } else {
        if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
            LastFetchOperationStatus = false;

            Log.e(TAG, "Authentication exception in fetching remote contacts");
            throw new AuthenticationException();
        } else {
            LastFetchOperationStatus = false;

            Log.e(TAG, "Server error in fetching remote contacts: ");
            throw new IOException();
        }
    }
    return friendList;
}

From source file:com.alibaba.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post/*from  w  w w  .j  a va 2s.c om*/
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file" + num + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.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());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}

From source file:com.pubkit.network.PubKitNetwork.java

public static JSONObject sendPost(String apiKey, JSONObject jsonObject) {
    URL url;//from w w  w .j  av a2s  . c o  m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(PUBKIT_API_URL);
        String encodedData = jsonObject.toString();
        byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length));
        connection.setRequestProperty("api_key", apiKey);

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

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(encodedData);//set data
        wr.flush();

        //Get Response
        InputStream inputStream = connection.getErrorStream(); //first check for error.
        if (inputStream == null) {
            inputStream = connection.getInputStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        wr.close();
        rd.close();

        String responseString = response.toString();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return new JSONObject("{'error':'" + responseString + "'}");
        } else {
            try {
                return new JSONObject(responseString);
            } catch (JSONException e) {
                Log.e("PUBKIT", "Error parsing data", e);
            }
        }
    } catch (Exception e) {
        Log.e("PUBKIT", "Network exception:", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:org.bibsonomy.util.WebUtils.java

/**
 * Sends a request to the given URL and checks, if it contains a redirect.
 * If it does, returns the redirect URL. Otherwise, returns null.
 * This is done up to {@value #MAX_REDIRECT_COUNT}-times until the final page is reached. 
 *  // w  w w .j a  va  2 s. co m
 * 
 * 
 * @param url
 * @return - The redirect URL.
 */
public static URL getRedirectUrl(final URL url) {
    try {
        URL internalUrl = url;
        URL previousUrl = null;
        int redirectCtr = 0;
        while (internalUrl != null && redirectCtr < MAX_REDIRECT_COUNT) {
            redirectCtr++;

            final HttpURLConnection urlConn = (HttpURLConnection) internalUrl.openConnection();

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

            /*
             * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some 
             * pages require it to download content.
             */
            urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE);

            urlConn.connect();

            // get URL to redirected resource
            previousUrl = internalUrl;
            try {
                internalUrl = new URL(urlConn.getHeaderField(LOCATION));
            } catch (final MalformedURLException e) {
                internalUrl = null;
            }

            urlConn.disconnect();

        }

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

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.// w w  w .java2 s.c o  m
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url/*from  w  ww.  ja va  2s . c  om*/
 *
 * @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              user.
 * @param password          password.
 * @return the file written.
 * @throws Exception if something goes wrong.
 */
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 && user.trim().length() > 0 && password.trim().length() > 0) {
        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_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.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();
        if (conn != null)
            conn.disconnect();
    }
    return file;
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 * //from   w w w  . j  a  va  2  s.  co m
 * @param url
 *            The URL to set up and receive content from
 * @return A valid HttpURLConnection
 * 
 * @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", getUserAgent());
    conn.setRequestProperty("User-Agent", getUserAgent());
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:org.akita.io.HttpInvoker.java

/**
 * post with files using URLConnection Impl
 * @param actionUrl URL to post//from   www  . j ava 2 s.c o m
 * @param params params to post
 * @param files files to post, support multi-files
 * @return response in String format
 * @throws IOException
 */
public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params,
        Map<String, File> files) throws AkInvokeException {
    try {
        Log.v(TAG, "post:" + actionUrl);
        if (params != null) {
            Log.v(TAG, "params:=====================");
            for (NameValuePair nvp : params) {
                Log.v(TAG, nvp.getName() + "=" + nvp.getValue());
            }
            Log.v(TAG, "params end:=====================");
        }

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setReadTimeout(60 * 1000);
        conn.setDoInput(true); // permit input
        conn.setDoOutput(true); // permit output
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post Method
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // firstly string params to add
        StringBuilder sb = new StringBuilder();
        for (NameValuePair nameValuePair : params) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(nameValuePair.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // send files secondly
        if (files != null) {
            int num = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
                num++;
                if (file.getKey() == null || file.getValue() == null)
                    continue;
                else {
                    if (!file.getValue().exists()) {
                        throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND,
                                "The file to upload is not found.");
                    }
                }
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.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());
            }
        }

        // request end flag
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // get response code
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        StringBuilder sb2 = new StringBuilder();
        if (res == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192);
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line + "\n");
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        Log.v(TAG, "response:" + sb2.toString());
        return sb2.toString();
    } catch (IOException ioe) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe);
    }
}