Example usage for javax.net.ssl HttpsURLConnection getHeaderFieldKey

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

Introduction

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

Prototype

public String getHeaderFieldKey(int n) 

Source Link

Document

Returns the key for the n th header field.

Usage

From source file:com.example.android.networkconnect.MainActivity.java

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//from   w  w  w  .j a v a2s. c  om

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        try {

            String headerName = null;

            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                //data=data+"Header Nme : " + headerName;
                //data=data+conn.getHeaderField(i);
                // Log.i (TAG,headerName);
                Log.i(TAG, headerName + ": " + conn.getHeaderField(i));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

        // conn= (HttpsURLConnection) url.wait(); ;
        //(HttpsURLConnection) url.openConnection();

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

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

private boolean login() {
    String url = null;/*w w w. j a v a2s. com*/

    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;
}

From source file:iracing.webapi.IracingWebApi.java

/**
 * // w w  w .  j a v a2 s  .co  m
 * @return a login response code
 * @throws IOException
 * @throws LoginException 
 * @see #LOGIN_RESPONSE_SUCCESS
 * @see #LOGIN_RESPONSE_CONNECTION_ERROR
 * @see #LOGIN_RESPONSE_DOWN_FOR_MAINTAINENCE
 * @see #LOGIN_RESPONSE_FAILED_CREDENTIALS
 */
public LoginResponse login() throws IOException, LoginException {
    try {
        installCerts();
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new LoginException("error whilst attempting to install SSL certificates");
    }

    System.setProperty("javax.net.ssl.trustStore", "jssecacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", CERT_STORE_PASSWORD);

    if (loginRequiredHandler == null)
        return LoginResponse.ConfigError;
    IracingLoginCredentials creds = new IracingLoginCredentials();
    if (!loginRequiredHandler.onLoginCredentialsRequired(creds))
        return LoginResponse.CredentialsError;
    String encodedUsername = URLEncoder.encode(creds.getEmailAddress(), "UTF-8");
    String encodedPW = URLEncoder.encode(creds.getPassword(), "UTF-8");

    String urltext = LOGIN_URL + "?username=" + encodedUsername + "&password=" + encodedPW; // + "&utcoffset=-60&todaysdate=";

    URL url = new URL(urltext);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.addRequestProperty("Content-Length", "0");

    conn.setInstanceFollowRedirects(false);
    HttpsURLConnection.setFollowRedirects(false);

    try {
        conn.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException(e.getMessage());
    }

    if (isMaintenancePage(conn))
        return LoginResponse.DownForMaintenance;

    String headerName;
    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase(SET_COOKIE)) {
            addToCookieMap(conn.getHeaderField(i));
        } else {
            if (!headerName.equals("Location")) {
                continue;
            }
            String location2 = conn.getHeaderField(i);

            if (location2.indexOf("failedlogin") != -1) {
                throw new LoginException("You have been directed to the failed login page");
            }
        }
    }
    createCookieFromMap();

    conn.disconnect();

    return LoginResponse.Success;
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();/*from w  w w  . jav a2  s. c o  m*/

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:com.kimbrelk.da.oauth2.OAuth2.java

protected final JSONObject requestJSON(Verb verb, String url, String postData) {
    try {/*from  ww  w  . j  av  a 2  s.c om*/
        mLog.append("SEND:\n");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", mUserAgent);
        connection.setRequestProperty("dA-minor-version", "" + VERSION.getMinor());
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        mLog.append(verb.toString() + " ");
        mLog.append(url);
        mLog.append("\n");
        connection.setRequestMethod(verb.toString());
        if (verb == Verb.POST) {
            mLog.append(postData);
            mLog.append("\n");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Authorization", "Basic " + base64(CLIENT_ID + ":" + loadLast()));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + postData.length());
            connection.connect();
            OutputStream os = connection.getOutputStream();
            os.write(postData.getBytes());
            os.flush();
        } else if (verb == Verb.GET) {
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.connect();
        }
        mLog.append("\nRECV:\n");

        try {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            String line = "";
            String page = "";
            while ((line = in.readLine()) != null) {
                page += line;
            }
            mLog.append(page);
            mLog.append("\n\n");
            return new JSONObject(page);
        } catch (Exception e) {
            try {
                JSONObject json = new JSONObject();
                json.put("status", "error");
                try {
                    InputStream is = connection.getErrorStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader in = new BufferedReader(isr);
                    String line = "";
                    String page = "";
                    while ((line = in.readLine()) != null) {
                        page += line;
                    }
                    mLog.append(page);
                    mLog.append("\n\n");
                    return new JSONObject(page);
                } catch (Exception err) {

                }
                try {
                    if (connection.getResponseCode() == 403 || connection.getResponseCode() == 429) {
                        json.put("error_description", RespError.RATE_LIMIT.getDescription());
                        json.put("error", RespError.RATE_LIMIT.getType());
                        return json;
                    }
                } catch (IOException er) {

                }
                String str = "";
                str += "URL: " + url.split("[?]+")[0] + "\n";
                //str += "POST Data: " + postData + "\n";
                str += "\n";
                for (int a = 0; a < connection.getHeaderFields().size() - 1; a++) {
                    str += connection.getHeaderFieldKey(a) + ": " + connection.getHeaderField(a) + "\n";
                }
                json.put("error_description", str);
                json.put("error", RespError.REQUEST_FAILED.getType());
                return json;
            } catch (Exception er) {
                throw e;
            }
        } finally {
            connection.disconnect();
        }
    } catch (Exception e) {
        try {
            e.printStackTrace();
            JSONObject json = new JSONObject();
            json.put("status", "error");
            json.put("error", RespError.REQUEST_FAILED.getType());
            json.put("error_description", RespError.REQUEST_FAILED.getDescription() + " : " + e);
            return json;
        } catch (JSONException er) {
            er.printStackTrace();
            return null;
        }
    }
}