Example usage for javax.net.ssl HttpsURLConnection getHeaderField

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

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);/*  w w w  .  j a  v  a2  s.  c o m*/
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

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

/**
 * //w w  w. j  av  a2s.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:in.rab.ordboken.NeClient.java

private void loginMainSite() throws IOException, LoginException {
    ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("_save_loginForm", "true"));
    data.add(new BasicNameValuePair("redir", "/success"));
    data.add(new BasicNameValuePair("redirFail", "/fail"));
    data.add(new BasicNameValuePair("userName", mUsername));
    data.add(new BasicNameValuePair("passWord", mPassword));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data);

    URL url = new URL("https://www.ne.se/user/login.jsp");
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setInstanceFollowRedirects(false);
    https.setFixedLengthStreamingMode((int) entity.getContentLength());
    https.setDoOutput(true);/*from w  w w.j  a  v a2  s  .  co  m*/

    try {
        OutputStream output = https.getOutputStream();
        entity.writeTo(output);
        output.close();

        Integer response = https.getResponseCode();
        if (response != 302) {
            throw new LoginException("Unexpected response: " + response);
        }

        String location = https.getHeaderField("Location");
        if (!location.contains("/success")) {
            throw new LoginException("Failed to login");
        }
    } finally {
        https.disconnect();
    }
}

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

void handleProxyRequest(Connection connection, HttpServletResponse resp, String verb, String url,
        @Nullable String referer, @Nullable String postData, boolean json, String site) throws IOException {
    HttpsURLConnection urlConnection;
    try {//  w  w w  .j  a va  2  s . c  om
        Map<String, String> headers = null;
        if (referer != null) {
            headers = new HashMap<String, String>();
            headers.put("Referer", referer);
        }

        urlConnection = connection.makeRequest(verb, url, postData, json, false, headers);
        if (urlConnection.getResponseCode() == 302) {
            {
                String location = urlConnection.getHeaderField("location");
                if (location.contains("/ap/maplanding")) {

                    try {
                        connection.registerConnectionAsApp(location);
                        account.setConnection(connection);
                        handleDefaultPageResult(resp, "Login succeeded", connection);
                        this.connectionToInitialize = null;
                        return;
                    } catch (URISyntaxException | ConnectionException e) {
                        returnError(resp, "Login to '" + connection.getAmazonSite() + "' failed: "
                                + e.getLocalizedMessage());
                        this.connectionToInitialize = null;
                        return;
                    }

                }

                String startString = "https://www." + connection.getAmazonSite() + "/";
                String newLocation = null;
                if (location.startsWith(startString) && connection.getIsLoggedIn()) {
                    newLocation = servletUrl + PROXY_URI_PART + location.substring(startString.length());
                } else if (location.startsWith(startString)) {
                    newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
                } else {
                    startString = "/";
                    if (location.startsWith(startString)) {
                        newLocation = servletUrl + FORWARD_URI_PART + location.substring(startString.length());
                    }
                }
                if (newLocation != null) {
                    logger.debug("Redirect mapped from {} to {}", location, newLocation);

                    resp.sendRedirect(newLocation);
                    return;
                }
                returnError(resp, "Invalid redirect to '" + location + "'");
                return;
            }
        }
    } catch (URISyntaxException | ConnectionException e) {
        returnError(resp, e.getLocalizedMessage());
        return;
    }
    String response = connection.convertStream(urlConnection);
    returnHtml(connection, resp, response, site);
}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {/*www .j  a  v  a 2s .  c o  m*/
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}

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 ww  .ja va  2s .  co  m*/

        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;/*from   w  w  w  . j  av  a  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;
}

From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a https post request
 *
 * @param url         request url//from   w w  w. java2  s.  c  o m
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a https post request
 */
public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    if (!sessionId.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }//from   ww w .  j  a va  2 s.  c  o m
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:iracing.webapi.IracingWebApi.java

/**
 * //from  w  w  w.  j  a  v  a  2 s  .  c o 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;
}