Example usage for javax.net.ssl HttpsURLConnection getInputStream

List of usage examples for javax.net.ssl HttpsURLConnection getInputStream

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.microsoft.onenote.pickerlib.ApiRequestAsyncTask.java

private JSONObject getJSONResponse(String endpoint) throws Exception {
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) (new URL(endpoint)).openConnection();
    mUrlConnection.setRequestProperty("User-Agent",
            System.getProperty("http.agent") + " Android OneNotePicker");
    if (mAccessToken != null) {
        mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
    }//from  w w w . j a va2s. co  m
    mUrlConnection.connect();

    int responseCode = mUrlConnection.getResponseCode();
    String responseMessage = mUrlConnection.getResponseMessage();
    String responseBody = null;
    boolean responseIsJson = mUrlConnection.getContentType().contains("application/json");
    JSONObject responseObject;
    if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
        mUrlConnection.disconnect();
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Invalid or missing access token.", null);
    }
    if (responseIsJson) {
        InputStream is = null;
        try {
            if (responseCode == HttpsURLConnection.HTTP_INTERNAL_ERROR) {
                is = mUrlConnection.getErrorStream();
            } else {
                is = mUrlConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            String lineSeparator = System.getProperty("line.separator");
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                buffer.append(lineSeparator);
            }
            responseBody = buffer.toString();
        } finally {
            if (is != null) {
                is.close();
            }
            mUrlConnection.disconnect();
        }

        responseObject = new JSONObject(responseBody);
    } else {
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Unrecognized server response", null);
    }

    return responseObject;
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /* w  ww. j a  v  a  2 s .  co  m*/
 * @param strURL ?URL
 * @return jsonStr JSON??
 */
protected String sendHttpRequest(final String strURL) {
    String jsonStr = "";
    try {
        URL url = new URL(strURL);
        /*---------make and set HTTP header-------*/
        //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection();
        HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection());

        /*---------show HTTP header information-------*/
        System.out.println("\n ---------http header---------- ");
        Map headers = con.getHeaderFields();
        for (Object key : headers.keySet()) {
            System.out.println(key + ": " + headers.get(key));
        }
        con.connect();

        /*---------get HTTP body information---------*/
        String contentType = con.getHeaderField("Content-Type");
        //String charSet = "Shift-JIS";// "ISO-8859-1";
        String charSet = "UTF-8";// "ISO-8859-1";
        for (String elm : contentType.replace(" ", "").split(";")) {
            if (elm.startsWith("charset=")) {
                charSet = elm.substring(8);
                break;
            }
        }

        /*---------show HTTP body information----------*/
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet));
        } catch (Exception e_) {
            System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
            br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet));
        }
        System.out.println("\n ---------show HTTP body information----------");
        String line = "";
        while ((line = br.readLine()) != null) {
            jsonStr += line;
        }
        br.close();
        con.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(jsonStr);
    return jsonStr;
}

From source file:org.comixwall.pffw.GraphsBase.java

/**
 * Run the controller task./*from ww  w  .  j a  va2 s . co  m*/
 * We fetch the graphs using secure http, or fall back to plain http if secure connection fails.
 * <p>
 * Note that the PFFW uses a self-signed server certificate. So the code should trust that certificate
 * and not reject the hostname.
 *
 * @return True on success, false on failure.
 */
@Override
public boolean executeTask() {
    Boolean retval = true;
    try {
        String output = controller.execute("symon", "RenderLayout", mLayout, mGraphWidth, mGraphHeight);

        JSONArray jsonArray = new JSONArray(output);
        mGraphsJsonObject = new JSONObject(jsonArray.get(0).toString());

        Iterator<String> it = mGraphsJsonObject.keys();
        while (it.hasNext()) {
            String title = it.next();
            String file = mGraphsJsonObject.getString(title);

            try {
                InputStream stream = null;

                try {
                    String outputGraph = controller.execute("symon", "GetGraph", file);
                    String base64Graph = new JSONArray(outputGraph).get(0).toString();
                    stream = new ByteArrayInputStream(Base64.decode(base64Graph, Base64.DEFAULT));

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warning("SSH graph connection exception: " + e.toString());
                }

                // Try secure http if ssh fails
                if (stream == null) {
                    // 1540861800_404e00f4044d07242a77f802e457f774
                    String hash = file.substring(file.indexOf('_') + 1);

                    try {
                        // Using https here gives: CertPathValidatorException: Trust anchor for certification path not found.
                        // So we should trust the PFFW server crt and hostname
                        URL secureUrl = new URL("https://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpsURLConnection secureUrlConn = (HttpsURLConnection) secureUrl.openConnection();

                        // Tell the URLConnection to use a SocketFactory from our SSLContext
                        secureUrlConn.setSSLSocketFactory(sslContext.getSocketFactory());

                        // Install the PFFW host verifier
                        secureUrlConn.setHostnameVerifier(hostnameVerifier);

                        logger.finest("Using secure http: " + secureUrl.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        secureUrlConn.setConnectTimeout(5000);
                        secureUrlConn.setReadTimeout(5000);
                        logger.finest("Secure URL connection timeout values: "
                                + secureUrlConn.getConnectTimeout() + ", " + secureUrlConn.getReadTimeout());

                        stream = secureUrlConn.getInputStream();

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.warning("Secure URL connection exception: " + e.toString());
                    }

                    // Try plain http if secure http fails
                    if (stream == null) {
                        // ATTENTION: Don't use try-catch here, catch in the outer exception handling
                        URL plainUrl = new URL("http://" + controller.getHost() + "/symon/graph.php?" + hash);

                        HttpURLConnection plainUrlConn = (HttpURLConnection) plainUrl.openConnection();

                        logger.finest("Using plain http: " + plainUrlConn.toString());

                        // ATTENTION: Setting a timeout value enables SocketTimeoutException, set both timeouts
                        plainUrlConn.setConnectTimeout(5000);
                        plainUrlConn.setReadTimeout(5000);
                        logger.finest("Plain URL connection timeout values: " + plainUrlConn.getConnectTimeout()
                                + ", " + plainUrlConn.getReadTimeout());

                        stream = plainUrlConn.getInputStream();
                    }
                }

                Bitmap bmp = BitmapFactory.decodeStream(stream);
                setBitmap(title, bmp);

            } catch (Exception e) {
                // We are especially interested in SocketTimeoutException, but catch all
                e.printStackTrace();
                logger.info("GraphsBase doInBackground exception: " + e.toString());
                // We should break out of while loop on exception, because all conn attempts have failed
                break;
            }
        }

        output = controller.execute("pf", "GetReloadRate");

        int timeout = Integer.parseInt(new JSONArray(output).get(0).toString());
        mRefreshTimeout = timeout < 10 ? 10 : timeout;

    } catch (Exception e) {
        e.printStackTrace();
        logger.warning("doInBackground exception: " + e.toString());
        retval = false;
    }
    return retval;
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String convertStream(HttpsURLConnection connection) throws IOException {
    InputStream input = connection.getInputStream();
    if (input == null) {
        return "";
    }/*  w w  w .j av  a2 s. c o m*/

    InputStream readerStream;
    if (StringUtils.equalsIgnoreCase(connection.getContentEncoding(), "gzip")) {
        readerStream = new GZIPInputStream(connection.getInputStream());
    } else {
        readerStream = input;
    }
    String contentType = connection.getContentType();
    String charSet = null;
    if (contentType != null) {
        Matcher m = charsetPattern.matcher(contentType);
        if (m.find()) {
            charSet = m.group(1).trim().toUpperCase();
        }
    }

    Scanner inputScanner = StringUtils.isEmpty(charSet)
            ? new Scanner(readerStream, StandardCharsets.UTF_8.name())
            : new Scanner(readerStream, charSet);
    Scanner scannerWithoutDelimiter = inputScanner.useDelimiter("\\A");
    String result = scannerWithoutDelimiter.hasNext() ? scannerWithoutDelimiter.next() : null;
    inputScanner.close();
    scannerWithoutDelimiter.close();
    input.close();
    if (result == null) {
        result = "";
    }
    return result;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

private String sendToController(String url, String urlParameters, String method) {
    try {//from  w w w.  j a v  a  2  s  .  c o m
        synchronized (cookies) {
            byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

            URL cookieUrl = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();

            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(method);
            //for(String cookie : cookies) {
            connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1));
            //}

            if (urlParameters.length() > 0) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
                connection.setUseCaches(false);

                try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                    wr.write(postData);
                }
            }

            InputStream response = connection.getInputStream();
            String line = readResponse(response);
            if (!checkResponse(line)) {
                logger.error("Unifi response: " + line);

            }
            return line;
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot send data " + urlParameters + " to url " + url + ". Exception: " + e.toString());
    }
    return "";
}

From source file:com.wso2telco.gsma.authenticators.mepin.MePinQuery.java

/**
 * Post request.//from   w  w w .  j  a va 2 s  .c  o m
 *
 * @param url     the url
 * @param query   the query
 * @param charset the charset
 * @return the string
 * @throws IOException                  Signals that an I/O exception has occurred.
 * @throws XPathExpressionException     the x path expression exception
 * @throws SAXException                 the SAX exception
 * @throws ParserConfigurationException the parser configuration exception
 */
private String postRequest(String url, String query, String charset)
        throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {

    HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

    ReadMobileConnectConfig readMobileConnectConfig = new ReadMobileConnectConfig();
    Map<String, String> readMobileConnectConfigResult;
    readMobileConnectConfigResult = readMobileConnectConfig.query("MePIN");
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
    connection.setRequestProperty("Authorization", "Basic " + readMobileConnectConfigResult.get("AuthToken"));
    //        connection.setRequestProperty("Authorization", "Basic "+mePinConfig.getAuthToken());

    OutputStream output = connection.getOutputStream();
    String responseString = "";

    output.write(query.getBytes(charset));

    int status = connection.getResponseCode();

    if (log.isDebugEnabled()) {
        log.debug("MePIN Response Code :" + status);
    }

    try {
        switch (status) {
        case 200:
        case 201:
        case 400:
        case 403:
        case 404:
        case 500:
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            break;
        }
    } catch (Exception httpex) {
        if (connection.getErrorStream() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("MePIN Response :" + responseString);
    }
    return responseString;
}

From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java

public int fetchUserRank() {
    AccessToken accessToken = CacheUtils.getAccessToken(context);
    if (accessToken == null) {
        return -1;
    }/*  w w  w  .  j  a  v a2s. com*/

    HttpsURLConnection urlConnection = null;
    BufferedReader reader = null;

    String jsonStr;
    try {

        final String LEADER_PATH = "leaders";
        final String API_SUFFIX = "api/v1";
        final String CLIENT_SECRET = "secret";
        final String APP_SECRET = "app_secret";
        final String ACCESS_TOKEN = "token";

        Uri.Builder builder;

        builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon();
        builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH)
                .appendQueryParameter(APP_SECRET, BuildConfig.CLIENT_ID)
                .appendQueryParameter(CLIENT_SECRET, BuildConfig.CLIENT_SECRET)
                .appendQueryParameter(ACCESS_TOKEN, accessToken.getAccessToken()).build();

        URL url = new URL(builder.toString());

        // Create the request to Wakatime.com, and open the connection

        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a string
        InputStream inputStream = urlConnection.getInputStream();
        StringBuilder buffer = new StringBuilder();
        if (inputStream == null) {
            return -1;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        if (buffer.length() == 0) {
            return -1;
        }
        jsonStr = buffer.toString();

        JSONObject currentUser = new JSONObject(jsonStr).getJSONObject("current_user");
        if (currentUser == null) {
            return -1;
        } else {
            //if is a new user, it'll result throw JSONException, because rank=null
            return currentUser.getInt("rank");
        }

    } catch (IOException e) {
        Timber.e(e, "IO Error");
        return -1;
    } catch (JSONException e) {
        Timber.e(e, "JSON error");
        return -1;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                Timber.e(e, "Error closing stream");
            }
        }
    }

}

From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java

private List<String> fetchLeaderBoardJson() {
    HttpsURLConnection urlConnection = null;
    BufferedReader reader = null;

    List<String> jsonDataList = new ArrayList<>();
    try {//from  ww w .  j  a va  2s  . c o  m

        final String LEADER_PATH = "leaders";
        final String API_SUFFIX = "api/v1";
        final String API_KEY = "api_key";
        final String PAGE = "page";

        Uri.Builder builder;
        String jsonStr;

        int totalPages = -1;
        int page = 1;
        do {

            builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon();
            builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH)
                    .appendQueryParameter(API_KEY, BuildConfig.API_KEY)
                    .appendQueryParameter(PAGE, String.valueOf(page)).build();

            URL url = new URL(builder.toString());

            // Create the request to Wakatime.com, and open the connection

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a string
            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            if (buffer.length() == 0) {
                return null;
            }
            jsonStr = buffer.toString();
            jsonDataList.add(jsonStr);

            //parse totalpages
            if (totalPages == -1) {
                totalPages = new JSONObject(jsonStr).getInt("total_pages");
            }
            page++;
        } while (totalPages != page);
    } catch (IOException e) {
        Timber.e(e, "IO Error");
    } catch (JSONException e) {
        Timber.e(e, "JSON error");
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                Timber.e(e, "Error closing stream");
            }
        }
    }
    return jsonDataList;
}

From source file:com.mb.ext.web.controller.UserController.java

/**
 * // w w  w.  j a va  2 s .co  m
 * get news
 * 
 */
@RequestMapping(value = "/pay", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public ResultDTO pay(@RequestBody PayDTO payDTO, HttpServletRequest request) {
    ResultDTO resultDTO = new ResultDTO();
    PayRequest payRequest = new PayRequest();
    payRequest.setAppid(WechatConstants.APPID_VALUE);
    payRequest.setMch_id(WechatConstants.MERCHANT_ID);
    payRequest.setNonce_str(RandomStringUtils.randomAlphanumeric(32));
    payRequest.setOut_trade_no(payDTO.getOut_trade_no());
    try {
        OrderDTO orderDTO = userService.getOrderByNumber(payDTO.getOut_trade_no());
        String productName = orderDTO.getProductName();
        BigDecimal amount = orderDTO.getPreAmount();
        payRequest.setBody(productName);
        payRequest.setTotal_fee(amount.multiply(new BigDecimal(100)).intValue());
        payRequest.setSpbill_create_ip(request.getRemoteAddr());
        payRequest.setNotify_url(WechatConstants.NOTIFY_URL);
        payRequest.setTrade_type("APP");
        payRequest.setAttach("ZHONGHUANBO");
    } catch (Exception e) {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    }

    payRequest.setSign(getSign(payRequest));
    //xml
    XStream xstreamRes = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // CDATA
                boolean cdata = true;

                @SuppressWarnings("rawtypes")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }

                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });
    XStream xstreamReq = new XStream(new XppDriver() /*{
                                                     public HierarchicalStreamWriter createWriter(Writer out) {
                                                     return new PrettyPrintWriter(out) {
                                                     // CDATA
                                                     boolean cdata = true;
                                                             
                                                     @SuppressWarnings("rawtypes")
                                                     public void startNode(String name, Class clazz) {
                                                     super.startNode(name, clazz);
                                                     }
                                                             
                                                     protected void writeText(QuickWriter writer, String text) {
                                                     if (cdata) {
                                                     writer.write("<![CDATA[");
                                                     writer.write(text);
                                                     writer.write("]]>");
                                                     } else {
                                                     writer.write(text);
                                                     }
                                                     }
                                                     };
                                                     }
                                                     }*/);
    xstreamReq.alias("xml", payRequest.getClass());
    String requestXML = xstreamReq.toXML(payRequest).replace("\n", "").replace("__", "_");
    try {
        requestXML = new String(requestXML.getBytes("utf-8"), "iso-8859-1");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    //
    BufferedReader reader = null;
    InputStream is = null;
    DataOutputStream out = null;
    StringBuffer sbf = new StringBuffer();
    String wechatResponseStr = "";
    try {
        URL url = new URL(WechatConstants.UNIFIED_ORDER_URL);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(requestXML);
        out.flush();

        is = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }

        wechatResponseStr = sbf.toString();
    } catch (Exception e) {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    } finally {
        try {
            reader.close();
            is.close();
            out.close();
        } catch (IOException e) {
            resultDTO.setCode("1");
            resultDTO.setMessage("?");
            return resultDTO;
        }

    }

    //?
    xstreamRes.alias("xml", PayResponse.class);
    PayResponse payResponse = (PayResponse) xstreamRes.fromXML(wechatResponseStr);
    //MOCK MODE
    /*PayResponse payResponse = new PayResponse();
    payResponse.setPrepay_id("WX123456789009876543211234567890");
    payResponse.setMch_id("6749328409382943");
    payResponse.setNonce_str("764932874987392");
    payResponse.setTrade_type("APP");
    payResponse.setReturn_code("SUCCESS");
    payResponse.setResult_code("SUCCESS");*/

    if ("SUCCESS".equals(payResponse.getReturn_code()) && "SUCCESS".equals(payResponse.getResult_code())) {
        payDTO.setMch_id(payResponse.getMch_id());
        payDTO.setNonce_str(payResponse.getNonce_str());
        payDTO.setPrepay_id(payResponse.getPrepay_id());
        payDTO.setTrade_type(payResponse.getTrade_type());
        payDTO.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000));
        payDTO.setSign(getSignForClient(payDTO));
        resultDTO.setBody(payDTO);
        resultDTO.setCode("0");
        resultDTO.setMessage("??");
    } else {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    }

    return resultDTO;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

private boolean login() {
    String url = null;/*from  w ww.j  ava  2  s . c o  m*/

    try {
        url = getControllerUrl("api/login");
        String urlParameters = "{'username':'" + username + "','password':'" + password + "'}";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        URL cookieUrl = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Referer", getControllerUrl("login"));
        connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
        connection.setUseCaches(false);

        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(postData);
        }

        //get cookie
        cookies.clear();
        String headerName;
        for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equals("Set-Cookie")) {
                cookies.add(connection.getHeaderField(i));
            }
        }

        InputStream response = connection.getInputStream();
        String line = readResponse(response);
        logger.debug("Unifi response: " + line);
        return checkResponse(line);

    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Ubiquiti Unifi login cookie: " + e.toString());
    }
    return false;
}