Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from   w  ww . j  a va  2  s. c o m
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;//from w ww.j  a  v  a  2 s.  c o  m
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;/*from ww w.j a va  2 s.c om*/
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:foam.starwisp.NetworkManager.java

private void Request(String u, String type, String CallbackName) {
    try {//from w  w  w  .  ja  va 2s . co m
        Log.i("starwisp", "pinging: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("GET");
        con.setDoInput(true);
        // Starts the query
        con.connect();
        m_RequestHandler.sendMessage(
                Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName)));

    } catch (Exception e) {
        Log.i("starwisp", e.toString());
        e.printStackTrace();
    }
}

From source file:io.undertow.servlet.test.streams.AbstractServletInputStreamTestCase.java

private void runTestViaJavaImpl(final String message, String url) throws IOException {
    HttpURLConnection urlcon = null;
    try {//from  www.  ja  v  a2  s. c  om
        String uri = getBaseUrl() + "/servletContext/" + url;
        urlcon = (HttpURLConnection) new URL(uri).openConnection();
        urlcon.setInstanceFollowRedirects(true);
        urlcon.setRequestProperty("Connection", "close");
        urlcon.setRequestMethod("POST");
        urlcon.setDoInput(true);
        urlcon.setDoOutput(true);
        OutputStream os = urlcon.getOutputStream();
        os.write(message.getBytes());
        os.close();
        Assert.assertEquals(StatusCodes.OK, urlcon.getResponseCode());
        InputStream is = urlcon.getInputStream();

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        int len;
        while ((len = is.read(buf)) > 0) {
            bytes.write(buf, 0, len);
        }
        is.close();
        final String response = new String(bytes.toByteArray(), 0, bytes.size());
        if (!message.equals(response)) {
            System.out.println(String.format("response=%s", Hex.encodeHexString(response.getBytes())));
        }
        Assert.assertEquals(message, response);
    } finally {
        if (urlcon != null) {
            urlcon.disconnect();
        }
    }
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;/*from  ww w. j  a va 2  s. co m*/
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Make remote request to get all calls stored in Cozy
 *//*w w  w.ja va 2 s.  c o  m*/
public String getRemoteCalls() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                Call.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE,
                            "Reading calls on Cozy " + i + "/" + jsonArray.length() + "..."));
                    JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Call call = Call.getByRemoteId(callJson.get("_id").toString());
                    if (call == null) {
                        call = new Call(callJson);
                    } else {
                        call.setRemoteId(callJson.getString("_id"));
                        call.setCallerId(callJson.getString("callerId"));
                        call.setCallerNumber(callJson.getString("callerNumber"));
                        call.setDuration(callJson.getLong("duration"));
                        call.setDateAndTime(callJson.getString("dateAndTime"));
                        call.setType(callJson.getInt("type"));
                    }

                    call.save();

                    allCalls.add(call);
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:foam.starwisp.NetworkManager.java

private void Post(String u, String type, String data, String CallbackName) {
    try {//from w w  w  .  ja  v a 2  s  . c om
        Log.i("starwisp", "posting: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("data", data));

        OutputStream os = con.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();

        // Starts the query
        con.connect();
        m_RequestHandler.sendMessage(
                Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName)));

    } catch (Exception e) {
        Log.i("starwisp", e.toString());
        e.printStackTrace();
    }
}

From source file:com.ideateam.plugin.DownloadDB.java

/**
 * Executes the request and returns PluginResult.
 * /*from  w  ww  .  j  a  va  2 s.c o m*/
 * @param action
 *            The action to execute.
 * @param args
 *            JSONArry of arguments for the plugin.
 * @param callbackContext
 *            The callback context from which we were invoked.
 */
@SuppressLint("NewApi")
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("downloadDB")) {

        activity = this.cordova.getActivity();

        JSONObject obj = new JSONObject(args.getString(0));
        dbName = obj.getString("nameDB");
        url = obj.getString("url");
        Log.d(TAG, "!!! download zip DB from url: " + url);

        zipPath = activity.getApplicationContext().getFilesDir().getPath();
        zipPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/databases";

        Log.d(TAG, ".. !!! DB path: " + zipPath);

        this.callbackContext = callbackContext;
        isDownloaded = false;

        URL uri;
        try {
            uri = new URL(url);

            HttpURLConnection httpConnection = (HttpURLConnection) uri.openConnection();
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
            if (httpConnection.getResponseCode() != 200) {
                Log.d(TAG, "..callbackContext.error ");
                callbackContext.error("Zip don't exists");
                ((CordovaActivity) this.cordova.getActivity())
                        .sendJavascript("UART.system.Helper.downloadDB('error')");
                Log.d(TAG, "..callbackContext.error ");
                callbackContext.error("Zip don't exists");
                ((CordovaActivity) this.cordova.getActivity())
                        .sendJavascript("UART.system.Helper.downloadDB('error')");

            } else {
                DownloadFile();

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else if (action.equals("removeDB")) {

        cordova.getActivity().runOnUiThread(new Runnable() {

            public void run() {

                Log.d(TAG, "... removeDB name " + dbName);

                try {
                    JSONObject obj = new JSONObject(args.getString(0));

                    String dbName = obj.getString("nameDB");

                    DeviceDB dDB = GetDeviceDB(dbName);

                    int deletedRows = dDB.master_db.delete("Databases", "name='" + dbName + "'", null);
                    dDB.master_db.close();

                    File file = new File(dDB.cordovaDBPath + dDB.cordovaDBName);
                    Boolean isDeleted = file.delete();

                    Log.d(TAG, "..removeDB path " + dDB.cordovaDBPath + dDB.cordovaDBName + " isDeleted "
                            + isDeleted + " del rows " + deletedRows);

                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.OK, args.optString(0)));

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });
    }

    else if (action.equals("sizeDB")) {

        cordova.getActivity().runOnUiThread(new Runnable() {

            JSONObject obj = new JSONObject(args.getString(0));
            String dbName = obj.getString("nameDB");

            DeviceDB dDB = GetDeviceDB(dbName);
            File file = new File(dDB.cordovaDBPath + dDB.cordovaDBName);

            public void run() {

                Log.d(TAG, ".. sizeDB dbName " + dbName);
                try {
                    CallbackResult(true, "" + file.length());
                    callbackContext.success("" + file.length());
                } catch (Exception e) {
                    //   Log.d(TAG, e.getMessage());

                }

            }
        });
    } else {
        return false;
    }
    Log.d(TAG, "..return from plugin");
    return true;
}

From source file:ch.cyberduck.core.gdocs.GDSession.java

@Override
protected void connect() throws IOException {
    if (this.isConnected()) {
        return;//from   www  .jav a  2 s .  c o m
    }
    this.fireConnectionWillOpenEvent();

    GoogleGDataRequest.Factory requestFactory = new GoogleGDataRequest.Factory();
    requestFactory.setConnectionSource(new HttpUrlConnectionSource() {
        public HttpURLConnection openConnection(URL url) throws IOException {
            return getConnection(url);
        }
    });
    GoogleAuthTokenFactory authFactory = new GoogleAuthTokenFactory(DocsService.DOCS_SERVICE,
            this.getUserAgent(), host.getProtocol().getScheme(), "www.google.com", client) {

        @Override
        public String getAuthToken(String username, String password, String captchaToken, String captchaAnswer,
                String serviceName, String applicationName, ClientLoginAccountType accountType)
                throws AuthenticationException {

            Map<String, String> params = new HashMap<String, String>();
            params.put("Email", username);
            params.put("Passwd", password);
            params.put("source", applicationName);
            params.put("service", serviceName);
            params.put("accountType", accountType.getValue());

            if (captchaToken != null) {
                params.put("logintoken", captchaToken);
            }
            if (captchaAnswer != null) {
                params.put("logincaptcha", captchaAnswer);
            }
            String postOutput;
            try {
                URL url = new URL(
                        host.getProtocol().getScheme() + "://" + "www.google.com" + GOOGLE_LOGIN_PATH);
                postOutput = request(url, params);
            } catch (IOException e) {
                AuthenticationException ae = new AuthenticationException(
                        Locale.localizedString("Connection failed", "Error"));
                ae.initCause(e);
                throw ae;
            }

            // Parse the output
            Map<String, String> tokenPairs = StringUtil.string2Map(postOutput.trim(), "\n", "=", true);
            String token = tokenPairs.get("Auth");
            if (token == null) {
                throw getAuthException(tokenPairs);
            }
            return token;
        }

        /**
         * Returns the respective {@code AuthenticationException} given the return
         * values from the login URI handler.
         *
         * @param pairs name/value pairs returned as a result of a bad authentication
         * @return the respective {@code AuthenticationException} for the given error
         */
        private AuthenticationException getAuthException(Map<String, String> pairs) {

            String errorName = pairs.get("Error");

            if ("BadAuthentication".equals(errorName)) {
                return new GoogleService.InvalidCredentialsException("Invalid credentials");

            } else if ("AccountDeleted".equals(errorName)) {
                return new GoogleService.AccountDeletedException("Account deleted");

            } else if ("AccountDisabled".equals(errorName)) {
                return new GoogleService.AccountDisabledException("Account disabled");

            } else if ("NotVerified".equals(errorName)) {
                return new GoogleService.NotVerifiedException("Not verified");

            } else if ("TermsNotAgreed".equals(errorName)) {
                return new GoogleService.TermsNotAgreedException("Terms not agreed");

            } else if ("ServiceUnavailable".equals(errorName)) {
                return new GoogleService.ServiceUnavailableException("Service unavailable");

            } else if ("CaptchaRequired".equals(errorName)) {

                String captchaPath = pairs.get("CaptchaUrl");
                StringBuilder captchaUrl = new StringBuilder();
                captchaUrl.append(host.getProtocol().getScheme()).append("://").append("www.google.com")
                        .append(GOOGLE_ACCOUNTS_PATH).append('/').append(captchaPath);
                return new GoogleService.CaptchaRequiredException("Captcha required", captchaUrl.toString(),
                        pairs.get("CaptchaToken"));

            } else {
                return new AuthenticationException("Error authenticating " + "(check service name)");
            }
        }

        /**
         * Makes a HTTP POST request to the provided {@code url} given the
         * provided {@code parameters}.  It returns the output from the POST
         * handler as a String object.
         *
         * @param url the URL to post the request
         * @param parameters the parameters to post to the handler
         * @return the output from the handler
         * @throws IOException if an I/O exception occurs while creating, writing,
         *                     or reading the request
         */
        private String request(URL url, Map<String, String> parameters) throws IOException {

            // Open connection
            HttpURLConnection urlConnection = getConnection(url);

            // Set properties of the connection
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // Form the POST parameters
            StringBuilder content = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                if (!first) {
                    content.append("&");
                }
                content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("=");
                content.append(CharEscapers.uriEscaper().escape(parameter.getValue()));
                first = false;
            }

            OutputStream outputStream = null;
            try {
                outputStream = urlConnection.getOutputStream();
                outputStream.write(content.toString().getBytes("utf-8"));
                outputStream.flush();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }

            // Retrieve the output
            InputStream inputStream = null;
            StringBuilder outputBuilder = new StringBuilder();
            try {
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }

                String string;
                if (inputStream != null) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    while (null != (string = reader.readLine())) {
                        outputBuilder.append(string).append('\n');
                    }
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return outputBuilder.toString();
        }
    };
    client = new DocsService(this.getUserAgent(), requestFactory, authFactory);
    client.setReadTimeout(this.timeout());
    client.setConnectTimeout(this.timeout());
    if (this.getHost().getProtocol().isSecure()) {
        client.useSsl();
    }

    if (!this.isConnected()) {
        throw new ConnectionCanceledException();
    }
    this.login();
    this.fireConnectionDidOpenEvent();
}