Example usage for javax.net.ssl HttpsURLConnection getResponseMessage

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

Introduction

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

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:org.openadaptor.util.PropertiesPoster.java

/**
 * Utility method which will attempt to POST the supplied properties information to the supplied URL.
 * //from   w  w  w  .  j  a va  2s  .  c  om
 * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more
 * secure trust manager which will use a cert store.
 * 
 * @param registrationURL
 * @param properties
 * @throws Exception
 */
protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception {

    URL url = new URL(registrationURL);
    String postData = generatePOSTData(properties);
    log.debug("Protocol: " + url.getProtocol());
    if (url.getProtocol().equals("https")) {

        // https connection

        // TODO: Replace this all trusting manager with one that uses a cert store
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection secureConnection = null;
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        secureConnection = (HttpsURLConnection) url.openConnection();
        secureConnection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = secureConnection.getResponseCode();
        if (HttpsURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL
                    + "\nData: " + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    } else {

        // Normal http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: "
                    + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];// ww w . j av a2s . c  o  m
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:com.clueride.auth.Auth0ConnectionImpl.java

@Override
public int makeRequest(URL auth0Url, String accessToken) throws IOException {

    /* Open Connection */
    HttpsURLConnection connection = (HttpsURLConnection) auth0Url.openConnection();

    /* Provide 'credentials' */
    connection.setRequestProperty("Authorization", "Bearer " + accessToken);

    /* Retrieve response */
    responseCode = connection.getResponseCode();
    responseMessage = connection.getResponseMessage();
    if (responseCode == 200) {
        InputStream inputStr = connection.getInputStream();
        String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding();
        jsonResponse = IOUtils.toString(inputStr, encoding);
        LOGGER.debug(String.format("Raw JSON Response:\n%s", jsonResponse));
    } else {/* w  w  w  . j  a  v a2s . co m*/
        LOGGER.error(String.format("Unable to read response: %d %s", responseCode, responseMessage));
    }
    return responseCode;
}

From source file:org.globusonline.transfer.JSONTransferAPIClient.java

public Result requestResult(String method, String path, JSONObject data, Map<String, String> queryParams)
        throws IOException, MalformedURLException, GeneralSecurityException, JSONException, APIError {
    String stringData = null;//from   ww  w . j  av  a2s . c  om
    if (data != null)
        stringData = data.toString();

    HttpsURLConnection c = request(method, path, stringData, queryParams);

    Result result = new Result();
    result.statusCode = c.getResponseCode();
    result.statusMessage = c.getResponseMessage();

    result.document = new JSONObject(readString(c.getInputStream()));

    c.disconnect();

    return result;
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getItemsDataFromRiotAPI() throws IOException, ParseException {
    String line;//from w  ww . j  av  a2  s  .c  o  m
    String result = "";
    URL url = new URL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=tags&api_key="
            + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getItemsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getChampionsDataFromRiotAPI() throws IOException, ParseException {
    String line;//  www.ja  v a 2 s .c o  m
    String result = "";
    URL url = new URL(
            "https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getChampionsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerIdDataFromRiotAPI(String region, String summonerName)
        throws MalformedURLException, IOException, ParseException {
    String line;//from  w w  w. j  ava  2  s.  com
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/"
            + summonerName + "?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerDataFromRiotAPI(String region, Long summonerID)
        throws MalformedURLException, IOException {
    String line;//w  w w.j a  v a  2 s  . c o  m
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/"
            + summonerID + "/entry?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

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 www. ja v a 2  s.  c o 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:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
        throws IOException, HttpResultException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);//from   w  ww  .  j a va2 s  .  co m
    nection.setDoOutput(true);
    nection.setConnectTimeout(2000);
    nection.setReadTimeout(1000);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
        nection.setRequestProperty("Authorization", "token " + accessToken);
    }

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

    try {

        nection.connect();

        int code = nection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) {
            throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage());
        }

        InputStream in = new BufferedInputStream(nection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            response.append(line);
        }

        try {
            return new JSONObject(response.toString());
        } catch (JSONException e) {
            throw new IOException(e);
        }

    } finally {
        nection.disconnect();
    }

}